# comparing vector elements

• 10-22-2008
l2u
comparing vector elements
Hello

I have 2 vectors which I want to compare if they contain the same element(s) (not all elements, just some specific). They hold 'some class' objects.

What would be the best way to compare those vector elements?

I've been thinking about reloading operator== in the class they contain, and the iterate through both vectors, something like:

Code:

```std::vector<some>::iterator it = v1.begin(), it2; for (; it != v1.end(); ++it) {         for (it2 = v2.begin(); it2 != v2.end(); ++it2) {                 if (*it == *it2) std::cout << "vectors contain the same element\n";         } }```
Is there any better/faster way of doing this?
Maybe some other container would be more suitable? Please note that I need random access iterator.

• 10-22-2008
matsp
You could use "find" instead of yourself iterating through the vector. If the vector you are searching in is sorted, you could use a binary search to locate a particular element.

If the lists are signficantly different size, you should iterate through the shorter one.

--
Mats
• 10-22-2008
l2u
Quote:

Originally Posted by matsp
You could use "find" instead of yourself iterating through the vector. If the vector you are searching in is sorted, you could use a binary search to locate a particular element.

If the lists are signficantly different size, you should iterate through the shorter one.

--
Mats

I looked at vector reference but I couldnt find 'find' member.

Are you sure it exists?

Thanks!
• 10-22-2008
matsp
I think it's in "algorithm" rather than in vector, because it works on all sorts of iteratable objects (including standard arrays).

Edit: http://www.cplusplus.com/reference/algorithm/find.html

--
Mats
• 10-22-2008
EOP
if the vectors are sorted:

set_intersection

http://www.cppreference.com/wiki/stl...t_intersection
• 10-22-2008
Daved
find might be slow - your loop would be O(m*n) where m is the number of objects in the first vector you want to search for and n is the number of objects in the second vector.

Hopefully your vectors are sorted (or at least the second one) so you can use some of the other tools. Perhaps making a third vector that contains only the elements from the first vector that you want to search for, and then using set_intersection or something similar to verify that it is a subset of the second vector.