Note that there are some explanatory texts on larger screens.

plurals
  1. PORework for loop over STL container to use functional techniques
    text
    copied!<p>I have a <code>std::vector</code> of pointers <code>Person</code> objects, which have a member function <code>std::string getName() const</code>. Using STL algorithms I want to count all the <code>Person</code> objects in the vector where <code>getName()</code> returns "Chad".</p> <p>The behaviour simply iterating over the loop would be:</p> <pre><code>int num_chads = 0; for(std::vector&lt;Person *&gt;::const_iterator it = vec.begin(); it != vec.end(); ++it) { if((*it)-&gt;getName() == "Chad") ++num_chads; } </code></pre> <p>I want to rework this so it uses all STL algorithms and functors etc (make it more functional-oriented). This is what I think I need to do:</p> <pre><code>const int num_chads = std::count_if(vec.begin(), vec.end(), std::bind1st(std::bind2nd(std::equal_to, mem_fun(Person::getName)), "Chad")); </code></pre> <p>As you can probably tell this doesn't work. Firstly, as I understand it, you can't use bind1st/bind2nd on binder1st/binder2nd objects as they are specifically designed to work with <code>std::binary_functions</code>. Secondly, and much more importantly, I don't think I am using the correct technique. I <em>do</em> want to bind one of the arguments to "Chad", but with the iterator argument I actually just want to transform the iterator value to a string before calling the bound version of <code>equals_to</code>.</p> <p>I think it is possible to do this using Boost, but is it possible using just the core C++03 (i.e. no C++0x lambas!)?</p> <p>EDIT: Can anyone come up with an example which does not use a user-defined predicate (i.e. just using the tools provided in the std toolkit)?</p> <p>EDIT: While Matthieu's answer is a textbook answer for how to use functors in STL algorithms, Cubbi's answer came from the approach I was looking for (although Mathieu did answer before I edited the question to make it more specific, so apologies there!). </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload