我有两个名为A和B的矢量对象.MyType类没有有一个字段ID,我想获得A中但不在B中的MyType *。 p>
由于我没有ID需要根据字符串字段进行比较。
我的对象的类看起来像这样
class Object
{
public:
Object();
string Name;
bool Mode;
string something;
Int range;
}
vector<Object*> a; //asssume filled with objects
vector<Object*> b; //asssume filled with objects
vector<Object*> ret;
现在我希望获得(a,b)
的差异 - 所有成员都在a而不是b。
如何继续这样做。我尝试使用strcmp()
进行比较,但它不起作用。
答案 0 :(得分:1)
将b
的所有条目添加到set。然后尝试将a
的所有条目添加到该集合中 - 成功的每个条目都是a
但不在b
中的条目。
如果是要比较的Name
条目,而不是指针,请使用set<string>
并将Name
条目添加到集合中。
答案 1 :(得分:1)
这使用现有的STL算法:
bool compPtrByName(Object *const &p1, Object *const &p2) {
return p1->Name < p2->Name;
}
然后致电
std::sort(a.begin(), a.end(), compPtrByName);
std::sort(b.begin(), b.end(), compPtrByName);
std::set_difference(a.begin(), a.end(), b.begin(), b.end(), ret.begin(), compPtrByName);
如果不允许重新排序向量,则先复制它们。
注意:这给出了集合差异A - B.对于对称差异(A - B)联合(B - A),使用std::set_symmetric_difference
。
答案 2 :(得分:-1)
对于set_difference
(http://www.cplusplus.com/reference/algorithm/set_difference/)来说,这似乎是一个完美的工作。
为对象提供比较器,对两个向量进行排序(使用该比较器),然后使用set_difference
(使用相同的比较器)获取第一个但不是第二个的对象。 / p>