c++ Difference between two vector<MyType*> A and B based on a string member

2.1k Views Asked by At

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.

Since I do not have an ID need to compare based on the string field.

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.

How to proceed on this. I tries using strcmp() to do the comparison but it is not working.

3

There are 3 best solutions below

0
On

This seems like a perfect job for 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.

3
On

Add all the entries of b into a set. 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.

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.

0
On

This uses the existing STL algorithm:

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.