C ++: comparing two vectors

Is there a way to compare two vectors?

if (vector1 == vector2) DoSomething(); 

Note: These vectors are not currently sorted and contain integer values.

+53
c ++ stdvector
Jun 06 '11 at 5:17
source share
3 answers

Note the std::mismatch C ++ method.

vector comparison was discussed on the DaniWeb forum , and also answered .

C ++: comparing two vectors

Check the bottom column SO. will help you. they achieved the same using the various-2 method.

Compare two C ++ vectors

+27
Jun 06 '11 at 5:19
source share

Your code ( vector1 == vector2 ) is the correct C ++ syntax. For vectors, the operator == exists.

If you want to compare a short vector with part of a longer vector, you can use the equal() operator for vectors. ( here )

Here is an example:

 using namespace std; if( equal(vector1.begin(), vector1.end(), vector2.begin()) ) DoSomething(); 
+48
Sep 29
source share

If they really need to stay unsorted (which they really donโ€™t do ... and if you are dealing with hundreds of thousands of elements, then I have to ask why you will compare such vectors), you can hack together a comparison method that works with unsorted arrays .

The only way to do this is to create a temporary vector3 and make it set_intersection by adding all the elements of vector1 to it, then search for each individual element of vector2 in vector3 and delete if found. I know this sounds awful, but why am I not writing any standard C ++ libraries in the near future.

In fact, just sort them first.

+1
Jun 06 2018-11-06T00:
source share



All Articles