1

Note: vector<int> vec = {0, 0, 0} return true

So I have a solution, it looks like this:

bool check(vector<char> vec)// can't think of a better name
{
    char firstChar {vec[0]};
    for (char i : vec)
    {
        if (i != firstChar)
            return false;
    }
    return true;
}

But since I'm a newbie, is there a better solution?

  • 3
    It doesn't look bad. A detail, here: `bool check(vector vec)` you are performing a copy of the vector. Better: `bool check_constant (const vector &vec)`. You can also use a `std::string` instead of a `std::vector`. – Damien Oct 21 '20 at 13:35
  • and don't forget to do a empty check first before getting vec[0] – RvdK Oct 21 '20 at 13:45
  • 1
    Assuming `vec` has at least one element, `std::count(vec.begin(), vec.end(), vec[0]) == vec.size()` will do it. Checking for at least one element is trivial. – Peter Oct 21 '20 at 15:39
  • 1
    Algorithmically, there is no fast method. Since you have to check all of the values. The best you can do is to stop after the first not equal value. Best case, the first value doesn't match. Worst case, all the values are equal (which means you processed all the array elements). Implementation of the algorithm may gain you some nanoseconds or best case, microseconds. – Thomas Matthews Oct 21 '20 at 16:25
  • 1
    I’d use `all_of` to capture what you are meaning. As in `std::all_of(vec.begin(), vec.end(), [&](const auto& x) { return x == vec.front(); }`. Note there’s no empty-case check because the predicate isn’t called in that case. If the extra equality check matters (if `==` is expensive) then it could be better to check the empty case. – Ben Oct 19 '21 at 03:14

0 Answers0