C++ 在c+中为包含数组的对象编写自定义std::set比较器+;
我想把我的问题简单化。我有一个以int数组作为成员变量的结构C++ 在c+中为包含数组的对象编写自定义std::set比较器+;,c++,stl-algorithm,C++,Stl Algorithm,我想把我的问题简单化。我有一个以int数组作为成员变量的结构 struct elem { elem (int a, int b, int c) {id[0]=a; id[1]=b; id[2]=c;} int id[3]; }; 我想将元素指针放入std::set,我想稍后使用find()从该集合中搜索特定对象,所以我想为这个std::set提供自定义比较器 struct compare { bool operator() (elem *one, elem *two )
struct elem
{
elem (int a, int b, int c) {id[0]=a; id[1]=b; id[2]=c;}
int id[3];
};
我想将元素指针放入std::set,我想稍后使用find()从该集合中搜索特定对象,所以我想为这个std::set提供自定义比较器
struct compare
{
bool operator() (elem *one, elem *two )
{
// logic
}
};
int main(int argc, char* argv[])
{
std::set< elem *, compare> elemSet;
std::set< elem *, compare>::iterator itr;
elem ob1(2,5,9), ob2(5,9,7), ob3(4,3,7);
elemSet.insert(&ob1);
elemSet.insert(&ob2);
elemSet.insert(&ob3);
elem temp(4,3,7);
itr = elemSet.find(&temp);
if(itr != elemSet.end())
{
cout << endl << (*itr)->id[0] << " " << (*itr)->id[1] << " " << (*itr)->id[2];
}
return 0;
}
结构比较
{
布尔运算符()(元素*1,元素*2)
{
//逻辑
}
};
int main(int argc,char*argv[])
{
标准:设置由于
std::set
(和std::map
及其multi
变体)需要,您需要通过比较器提供该排序。严格弱排序要求
(x < x) == false
(x < y) == !(y < x)
((x < y) && (y < z)) == (x < z)
还请注意,我将参数作为指向-
const
的指针,您需要什么样的帮助?只有您应该知道less运算符应该为您的类做什么。只需使用vector它就可以了。您需要什么样的语义来进行比较?@v01d-我不能使用vector,因为元素的数量可能超过2000万..I如果你有足够的内存来存储数组,那么使用vector就没有问题。我可能错了,只是不明白数组是如何通过这个元素计数存在的,而vector不会?
struct compare
{
bool operator() (elem const* one, elem const* two )
{ // take 'tie' either from Boost or recent stdlibs
return tie(one->id[0], one->id[1], one->id[2]) <
tie(two->id[0], two->id[1], two->id[2]);
}
};