I have written a bit of code to match two vector of objects that have some of the same instances of objects within both of the vectors.
The idea is to find the index of the object in the ‘main’ vector and match that to the object of the other vector.
The index of the main vector would then be used in a map with that object.
I think looking at the code may make my explanation a bit clearer:
ifndef OBJECTMAPMATCH_H
#define OBJECTMAPMATCH_H
#include <map>
#include <utility>
#include <vector>
#include <typeinfo>
#include <iostream>
#include <stdlib.h>
namespace ObjectMapMatch {
...
...
template< class A, class B >
std::map<int, B*>* getIndexMap( std::vector<A*>* x , std::vector<B*>* y, std::map<int, B*>* output )
{
typename std::vector<A*>::iterator Aitr = x->begin();
typename std::vector<A*>::iterator AitrE = x->end();
typename std::vector<B*>::iterator Bitr = y->begin();
typename std::vector<B*>::iterator BitrE = y->end();
for(int index=0; Aitr!=AitrE; ++Aitr, ++index){
//Keep track of original index
int AntupIndex = (*Aitr)->Index();
int match = false;
for(; Bitr!=BitrE; ++Bitr){
int BntupIndex = (*Bitr)->Index();
if( AntupIndex == BntupIndex ){
match = true;
output[index] = (*Bitr);
}
} //End of loop B
if(!match){
std::cout << "ERROR:ObjectMapMatch::getIndexMap: Can not Find Match" << typeid(y).name() << " FOR " << typeid(x).name() << std::endl;
exit(1);
}
}//End of Loop A
}
...
...
}
#endif
As you can see I am basically comparing the two objects with there unique index and if this matches the object will match.
My quesitons:
I know I could have overloaded the comparison operator in the object class, but I was not sure if something like this would be correct??
bool operator==(object1& lhs, object2& rhs){
&lhs == &rhs ? return true : return false;
}
Also,
Is there a shorter/more efficient way of the above code using some STL algorithms (can not use the boost libs) or something smarter??
Mike
There are couple of ways to do this more efficiently than O(n^2).
For example:
set_intersectionon sorted vectors.Or:
multiset(orunordered_multiset).multisetthat have more than one element indicate a match.For both of these methods, you could use pointers or indexes in original vectors instead of the actual elements. Just be careful to provide comparer (to
sort,set_intersectionandmultiset) able to deal with pointers/indexes.