Vector elements

How can I check, if all the elements in a vector are equal to each other or not?
I would make a boolean function.


1
2
3
4
5
6
7
8
bool vecSame(vector <int> vec) {
     for(int i = 0; i < vec.size(); ++i) {
          if(vec[0] != vec[i])
                return false;
     }

     return true; 
}


Just some algorithmic thinking is all. Basically it keeps comparing the first element to every element in the vector one at a time to make sure they are the same as the first element, (thus, they would all be the same). If it finds an element that doesn't match, it will return false, but if it makes it all the way through the for loop without returning false, it must be true, so there's a return true statement at the end.
Thanks! (:
Adding to the previous answer:

If you have a large vector, you can reduce runtime from O(n) to something like O(log(n)) by splitting the vector in half each time, e.g.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <typename T>
bool is_uniform(const std::vector<T>& vec, size_t pos1 = 0, size_t pos2 = 0){
    if(vec.empty())
        return false; //Because there is nothing to be uniform about
    else if((pos1 == pos2 && pos1 == 0) || (pos1 > pos2)){
        pos2 = vec.size() - 1;
        pos1 = 0;
    }
    if(pos1 == pos2)
        return true;
    else if(pos1 + 1 != pos2){
            //Avoid checking the second half if possible
        if(is_uniform(vec, pos1, (pos2-pos1)/2+pos1))
            return is_uniform(vec, (pos2-pos1)/2+pos1+1, pos2);
        else
            return false;
    }
    return vec[pos1] == vec[pos2];
}


You can extend this to work with iterators as well.
Topic archived. No new replies allowed.