[英]C++: How to check that an object with a specific property exists in a set
I have the following structure: 我有以下结构:
struct dependence {
dependence() {}
dependence(string CUid, LID sink, LID source, std::string var)
: CUid(CUid), sink(sink), source(source), var(var) {}
string CUid;
LID sink = 0;
LID source = 0;
std::string var;
};
Now I want to insert objects of this structure in a set. 现在,我想将这种结构的对象插入集合中。 I have objects with the same CUid
but (important!) the other properties ( sink
, source
, var
) can differ. 我有相同的对象CUid
但(重要!)的其他属性( sink
, source
, var
)可以不同。 I want to prevent inserting objects with the same CUid
in the set. 我想防止在集合中插入具有相同CUid
对象。 So the only way I know, is to iterate through the set and check each object of the CUid
. 因此,我知道的唯一方法是遍历集合并检查CUid
每个对象。 Is there a better way with less code to check for that? 有没有更好的方法用更少的代码进行检查?
You can use a custom comparator that defines the order in which your objects will be stored in the set. 您可以使用自定义比较器来定义对象在集合中的存储顺序。
struct cmp
{
bool operator()(const dependence &a,const dependence &b) const
{
return a.CUid < b.Cuid;
}
};
and then 接着
std::set<dependence,cmp> myset;
Now if you try to insert objects with same CUid
, only the first instance will go in myset
. 现在,如果你尝试插入具有相同的对象CUid
,只有第一个实例会在myset
。
EDIT: 编辑:
Another way would be to overload <
operator. 另一种方法是重载<
运算符。
bool operator<(const dependence &a,const dependence &b)
{
return (a.CUid<b.CUid);
}
and then 接着
std::set<dependence> myset;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.