Iterating over pair elements in a container of pairs (C++)
c++, containers, iterator, std-pair
Solution
To flatten your container of pairs into a second container you could also simply write your own inserter:
template<class C>
struct Inserter {
std::back_insert_iterator<C> in;
Inserter(C& c) : in(c) {}
void operator()(const std::pair<typename C::value_type, typename C::value_type>& p)
{
*in++ = p.first;
*in++ = p.second;
}
};
template<class C>
Inserter<C> make_inserter(C& c)
{
return Inserter<C>(c);
}
// usage example:
std::list<int> l;
std::for_each(a.begin(), a.end(), make_inserter(l));
Problem
If I have a container (`vector`, `list`, etc) where each element is a `std::pair`, is there an easy way to iterate over each element of each pair? i.e. ``` std::vector<std::pair<int,int> > a; a.push_back(std::pair(1,3)); a.push_back(std::pair(2,3)); a.push_back(std::pair(4,2)); a.push_back(std::pair(5,2)); a.push_back(std::pair(1,5)); ``` and then being able to iterate over the value: 1,3,2,3,4,2,5,2,1,5? Similarly, what type of functor/function would return to me a container (of the same type) with a flat listing of the pair elements as above?