I have next code:
#include
#include
#include
for (const auto& your_pair : your_container)
your_stream << "[" << your_pair.first << "," << your_pair.second << "]" << endl;
more simple and universal !
Here is an adaptor to use with std::copy
and std::ostream_iterator
for the std::pair
type. You end up holding one extra reference, but the compiler optimization may take care of it. BTW, the first type in std::pair
of the std::map::value_type
will be a const
.
template <typename pair_type>
class pair_adaptor
{
public:
const pair_type &m;
pair_adaptor(const pair_type &a) : m(a) {}
friend std::ostream &operator << (std::ostream &out,
const pair_adaptor <pair_type> &d)
{
const pair_type &m = d.m;
return out << m.first << " => " << m.second;
}
};
typedef std::map<size_t, size_t>::value_type value_type;
std::copy (mymap.begin(), mymap.end(),
std::ostream_iterator <
pair_adaptor <value_type> > (std::cout, "\n"));
std::copy (mymap.begin(), mymap.end(),
std::ostream_iterator <
pair_adaptor <
std::pair<const size_t, size_t>>> (std::cout, "\n"));
Just passing by, but this did the job for me, so it can for somebody else (cut version):
template<typename First, typename Second>
struct first_of {
First& operator()(std::pair<First, Second>& v) const {
return v.first;
}
};
Use case given:
transform (v.begin (), v.end (),
ostream_iterator<int>(cout, "\n"), first_of<int, string> ());
What you want is a transforming iterator. This kind of iterator wraps another iterator, forwards all positioning methods like operator++ and operator==, but redefines operator* and operator->.
Quick sketch :
template <typename ITER>
struct transformingIterator : private ITER {
transformingIterator(ITER const& base) : ITER(base) {}
transformingIterator& operator++() { ITER::operator++(); return *this; }
std::string operator*() const
{
ITER::value_type const& v = ITER::operator*();
return "[" + v->first +", " + v->second + "]";
}
...