std::copy to std::cout for std::pair

前端 未结 10 559
耶瑟儿~
耶瑟儿~ 2020-12-04 20:08

I have next code:

#include 
#include 
#include 
#include 

//namespace std
//{

std::ostream&         


        
相关标签:
10条回答
  • 2020-12-04 21:04
        for (const auto& your_pair : your_container)
            your_stream << "[" << your_pair.first << "," << your_pair.second << "]" << endl;
    

    more simple and universal !

    0 讨论(0)
  • 2020-12-04 21:04

    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"));
    
    0 讨论(0)
  • 2020-12-04 21:07

    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> ());
    
    0 讨论(0)
  • 2020-12-04 21:09

    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 + "]";
        }
    ...
    
    0 讨论(0)
提交回复
热议问题