Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if all elements of a vector are equal in C++

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.

like image 726
Ward9250 Avatar asked Nov 29 '13 13:11

Ward9250


People also ask

Can you use == on vectors C++?

As long as your vector contains elements that in themselves can be compared (have operator== ), this works, yes.

How do you know if two vectors are equal?

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.


1 Answers

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; } 
like image 146
Vlad from Moscow Avatar answered Sep 17 '22 10:09

Vlad from Moscow