[英]c++ Difference between two vector<MyType*> A and B based on a string member
I've got two vector objects called A and B. The MyType class does not have a field ID and I want to get the MyType* which are in A but not in B. 我有两个向量对象,分别称为A和B。MyType类没有字段ID,我想获取MyType *,它们位于A而不是B中。
Since I do not have an ID need to compare based on the string field. 由于我没有ID,因此需要根据字符串字段进行比较。
My object's class looks like this 我的对象的类看起来像这样
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;
Now I want to get diff of (a,b)
- all the members that are in a and not b. 现在我想获取
(a,b)
差异-a中的所有成员而不是b中的所有成员。
How to proceed on this. 如何进行此操作。 I tries using
strcmp()
to do the comparison but it is not working. 我尝试使用
strcmp()
进行比较,但无法正常工作。
Add all the entries of b
into a set . 将
b
所有条目添加到集合中 。 Then try to add all the entries of a
into that set -- each entry that succeeds is an entry that is in a
but not in b
. 然后尝试的所有条目添加
a
成集-即成功的每个条目是在进入a
但不是在b
。
If it's the Name
entries you want to compare, not the pointers, use a set<string>
and add the Name
entries to the set. 如果它是要比较的
Name
条目,而不是指针,请使用set<string>
并将Name
条目添加到集合中。
This uses the existing STL algorithm: 这使用现有的STL算法:
bool compPtrByName(Object *const &p1, Object *const &p2) {
return p1->Name < p2->Name;
}
and then call 然后打电话
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);
If reordering the vectors is not allowed, then copy them first. 如果不允许对向量进行重新排序,请先复制它们。
Note: This give the set difference A - B. For the symmetric difference (A - B) union (B - A), use std::set_symmetric_difference
. 注意:这给出了设置差异A-B。对于对称差异(A-B)并集(
std::set_symmetric_difference
-A),请使用std::set_symmetric_difference
。
This seems like a perfect job for set_difference
( http://www.cplusplus.com/reference/algorithm/set_difference/ ). 对于
set_difference
( http://www.cplusplus.com/reference/algorithm/set_difference/ ),这似乎是一项完美的工作。
Provide a comparator for your objects, sort the two vectors (using that comparator), and then use set_difference
(using that same comparator) to get the objects that are in the first, but not the second. 为您的对象提供一个比较器,对两个向量进行排序(使用该比较器),然后使用
set_difference
(使用相同的比较器)来获取第一个而不是第二个中的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.