C++ 中多重集的自定义 [] 访问
Custom [] access for mulltiset in C++
我正在使用多重集编写一段基本代码。而运行成问题了。我是 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) 的,你不能做得更好,至少在多重集上是这样。
我正在使用多重集编写一段基本代码。而运行成问题了。我是 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) 的,你不能做得更好,至少在多重集上是这样。