简体   繁体   中英

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.

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 .

Simply use operator == of vector:

std::vector<int> v1{1, 2, 3, 4}, v2{1, 2, 3, 4};
bool are_equal = (v1 == v2);

Equality operator ( == ) is overloaded in C++ Vector STL. So you can easily compare those directly like comparing two integers.

To compare row and column of a matrix as you said, use a loop and compare rows and columns directly by == .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM