Search code examples
c++stlstdvector

Count objects which have a field equal to a specific value


I have a vector of objects, and I'd like to count how many of them have a field equal to a specific value.

I can use a loop and count such elements, but I need to do this many times and I'd prefer a concise way of doing this.

I'm looking to do something like the pseudo code below

class MyObj {
public:
    std::string name;
}

std::vector<MyObj> objects

int calledJohn = count(objects,this->name,"john") // <- like this

Solution

  • If you're looking to count how many objects have a certain property, std::count_if is the way to go. std::count_if takes a range to iterate over and the functor object that will determine if the object has the value:

    auto calledJohn = std::count_if(std::begin(objects), std::end(objects),
                               [] (const MyObj& obj) { return obj.name == "John"; });