我正在使用多集编写基本的代码。并遇到了问题。我对STL还是很陌生,找不到特别有用的东西来帮助我自定义访问多集元素。

// Custom class - 3 integers and a Compare function
class Sums
{
    public:
        Sums(int v1, int v2, int v3) : val1(v1), val2(v2), val3(v3) {};
        bool operator<(const Sums &v) const { return val3 < v.val3; }

        int val1;
        int val2;
        int val3;
};

// Multiset using the above class, sorted using val3
multiset<Sums> b;
b.insert(Sums(1, 2, 11));
b.insert(Sums(0, 1, 20));

// This works.
auto i = b.find(Sums(1,2,11));
cout << i->val1 << ' ' << i->val2 << ' ' << i->val3 << endl;

/* But, suppose I only know that the element of the multiset which I have to find has val1=1 and val2=2, and I don't know the corresponding value of val3.
Is it possible to somehow overload the [] operator, so that the following works? Because, I can't use find() without knowing the values of all three data members of the class.*/

cout << b[1].val3 << endl;  // I want this to print 11.
cout << b[1][2].val3 << endl; // Is this also possible?

最佳答案

这应该做的工作:

#include <algorithm>

// Your struct / classes here

void foo() {
    multiset<Sums> b;
    b.insert(Sums(1, 2, 11));
    b.insert(Sums(0, 1, 20));

    auto i = std::find_if(b.cbegin(), b.cend(), [](const Sums &v) -> bool {
    return v.val1 == 1 && v.val2 == 2; });

}

该算法为O(n),并且至少使用多集时,您无法做得更好。

08-24 18:31