I have made a small example in order to understand how boost::bind () works with collections. I have a class called Data:
class Data
{
public:
void print ();
const std::string& get () const;
std::string& get () ;
};
I have created a std::vector of Data objects called samples and I am able to use bind in the same way as std::mem_fun_ref works.
std::for_each (samples.begin (),samples.end (),std::mem_fun_ref (&Data::print));
std::for_each (samples.begin (),samples.end (),boost::bind (&Data::print,_1));
The basic idea is that the bind returns a function object of type bind_t<RetType=void, ObjType=Data, ArgType=void>. The member function as the first parameter allows the compiler to deduce RetType, ObjType and ArgType. The placeholder _1 corresponds to the data object which must be provided by the algorithm.
Then std::for_each calls the function object "for each" element in the following way:
for ( ; first!=last; ++first ) f(*first);
bind_t::operator(ObjType& obj) is invoked and its definition should be something like this:
return (obj.*_method ());
I have crated a class called Filter that performs some processing over a data element.
class Filter
{
void filter (Data& data);
...
};
If I want to apply the filter over the data elements in the vector I call bind in the following way:
std::for_each (samples.begin (),samples.end (),boost::bind (&Filter::filter,filter,_1));
for_each passes a Data object to bind_t::operator(). In this case the function object already has the object and just need the parameter so in this case placeholder _1 refers to the argument.
Here comes my question:
How can use bind if I have to iterate over a std::map rather than a vector?
(Sorry for all the explanation, I just want to make sure that I understand the way in which bind works)