0

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.

AJ.
  • 2,561
  • 9
  • 46
  • 81

3 Answers3

1

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • I want to compare string fields of all the objects on two different vectors. Creating a set will only tell me what strings are unique but not return me the objects. – AJ. Oct 12 '12 at 09:14
  • Right, but you'll be going through the objects when that happens. So when the set tells you that a string is unique, return the object whose string you just added to the set. You will be going through the objects adding their names to the set. When you go through the objects in `a` (after going through `b`), each name that adds tells you that the object in `a` you were operating on should be returned. – David Schwartz Oct 12 '12 at 09:26
  • More complicated than necessary. – Paul Draper Mar 01 '13 at 05:49
1

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.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
-1

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.

Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40