If I have a vector of values and want to check that they are all the same, what is the best way to do this in C++ efficiently? If I were programming in some other language like R one way my minds jumps to is to return only the unique elements of the container and then if the length of the unique elements is more than 1, I know all the elements cannot be the same. In C++ this can be done like this:
//build an int vector std::sort(myvector.begin(), myvector.end()); std::vector<int>::iterator it; //Use unique algorithm to get the unique values. it = std::unique(myvector.begin(), myvector.end()); positions.resize(std::distance(myvector.begin(),it)); if (myvector.size() > 1) { std::cout << "All elements are not the same!" << std::endl; }
However reading on the internet and SO, I see other answers such using a set
or the find_if
algorithm. So what is the most efficient way of doing this and why? I imagine mine is not the best way since it involves sorting every element and then a resizing of the vector - but maybe I'm wrong.
As long as your vector contains elements that in themselves can be compared (have operator== ), this works, yes.
In simple words, we can say that two or more vectors are said to be equal vectors if their length is the same and they all point in the same direction. Generally, we can check for equal vectors by comparing their coordinates. If all the coordinates of two or more vectors are the same, then they are equal vectors.
You need not to use std::sort
. It can be done in a simpler way:
if ( std::adjacent_find( myvector.begin(), myvector.end(), std::not_equal_to<>() ) == myvector.end() ) { std::cout << "All elements are equal each other" << std::endl; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With