This is more of a learning question. Is there a way I can write the following for-loop using std::for_each or std::transform? If not, is there anything in boost that can help on this? The loop simply flattens a vector of vectors into one long vector.
vector<vector<int> > int_vectors;
// ... fill int_vectors
vector<int> ints;
for (vector<vector<int> >::const_iterator iter = int_vectors.begin(); iter != int_vectors.end(); ++iter) {
ints.insert(ints.end(), iter->begin(), iter->end());
}
I wouldn’t change this to use one of the algorithms unless you have a compiler that supports lambdas. It’s completely clear as written. Even if your compiler did support lambdas, I’d probably not change this code.
One relatively straightforward option would be to write a flattening iterator. I wrote one for demonstration in an answer to another question.
If you really want a one-liner and can use
bind(boost::bindfrom Boost,std::tr1::bindfrom TR1, andstd::bindfrom C++0x will all work), then here is how that would look. I warn you in advance: it is horrible.Edit: Technically this is also illegal. The type of a Standard Library member function is unspecified, so you cannot (portably or correctly) take the address of such a member function. If you could correctly take the address of a Standard Library member function, this is what it would look like:
(Yes, that is technically one “line of code” as it is a single statement. The only thing I have extracted is a typedef for the pointer-to-member-function type used to disambiguate the overloaded
beginandendfunctions; you don’t necessarily have to typedef this, but the code requires horizontal scrolling on Stack Overflow if I don’t.)