Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the FASTEST way to compare vectors in C++?

What is the fastest way to see if two vectors are equal in c++?

I'm trying to find the fastest way to see if any row is equal to any column of a matrix, so element by element comparison and exiting the loop when not equal is not good enough.

like image 594
Celi Manu Avatar asked Oct 20 '25 16:10

Celi Manu


1 Answers

Do not reinvent the wheel. You can use std::equal from <algorithm>.

It has the following complexity:

No applications of the corresponding predicate if InputIterator1 and InputIterator2 meet the requirements of random access iterators and last1 - first1 != last2 - first2. Otherwise, at most min(last1 - first1, last2 - first2) applications of the corresponding predicate.

That's what you were looking for.
See the documentation for further details.


As mentioned in the comments, there is a subtle difference between operator== and std::equal: the former doesn't work if types are different (as an example, std::vector<int> and std::vector<double>), the latter does work instead.
I tried to give the most generic solution.
If types are the same, of course operator== works like a charm, as mentioned by @Jarod42.

like image 104
skypjack Avatar answered Oct 23 '25 06:10

skypjack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!