Just for fun I was trying to write a one line with std::find_if with boost::bind to check whether all the keys given in a vector in a map has no values, but really could not come up with a neat line of code.
Here is what I attempted
vector<string> v;
v.push_back("a");
v.push_back("2");
...
map<string, string> m;
m.insert("b","f");
...
std::find_if(v.begin(), v.end(), boost::bind(&string::empty, boost::bind(&map<string,String>::operator[], _1), _2 )) != v.end();
Obviously this is a big fail… anyone tried something like this?
The following line of code returns
trueonly if all elements fromvare not present inm:Explanation:
Here we have two functors:
boost::bind<str_map_t::const_iterator>( &str_map_t::find, &m, _1 )This functor will return
const_iteratorwhich points to the element frommor tom.end()if not found. Here you should explicitly point return typestr_map_t::const_iteratorforboost::bindto get rid of ambiguity.boost::bind( &str_map_t::const_iterator::operator!=, _1, _2 )This one will return
trueif_1!=_2andfalseotherwise.Combine 1 and 2 and we’ll get the full code:
I wouldn’t say it is readable code and I’d recommend to write a custom functor to get it more readable. A more readable version could look like the following (without
bind):