This is a follow-up to my question from yesterday. I have Scott Meyers' warning about write-only code on my mind. I like the idea in principle of using standard algorithms to access the keys or values of a std::map, but the syntax required is a little baroque IMHO. Let's say I want to dump all the keys of a map to a vector. Given following declarations,
typedef std::map<int, int> MyMap;
MyMap m;
std::vector<int> v;
which code is more maintainable (i.e., potentially less confusing)?
Option #1:
std::transform(m.begin(),
m.end(),
std::back_inserter(v),
std::tr1::bind(&MyMap::value_type::first, _1));
Option #2:
for (MyMap::iterator i = m.begin(); i != m.end(); ++i)
{
v.push_back(i->first);
}
Option 1 is more standard library-ish but I have to mentally decompose it to understand what's going on. Option 2 seems easier to read at the expense of a possible small runtime penalty. I'm not hurting for CPU time so I'm leaning toward option 2. Does you guys agree? Is there a third option I should consider?
P.S. Over the course of writing this question I concluded that the best way (for my project) to read the keys of a std::map is to store them off in a side container and iterate over that. The maintainability question still stands though.