Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count objects which have a field equal to a specific value

Tags:

c++

stl

stdvector

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
like image 468
joeButler Avatar asked Apr 20 '26 05:04

joeButler


2 Answers

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"; });
like image 138
David G Avatar answered Apr 21 '26 22:04

David G


Use std::count_if

auto n = std::count_if(objects.begin(), objects.end(),
                       [](const MyObj& o) { return o.name == "john";});
like image 24
juanchopanza Avatar answered Apr 21 '26 21:04

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!