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

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

I have next code:

#include 
#include 
#include 
#include 

//namespace std
//{

std::ostream&         


        
10条回答
  •  爱一瞬间的悲伤
    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 
    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  &d)
        {
            const pair_type &m = d.m;
            return out << m.first << " => " << m.second;
        }
    };
    
    typedef std::map::value_type value_type;
    
    std::copy (mymap.begin(), mymap.end(),
        std::ostream_iterator < 
            pair_adaptor  > (std::cout, "\n"));
    
    std::copy (mymap.begin(), mymap.end(),
        std::ostream_iterator < 
            pair_adaptor <
                std::pair>> (std::cout, "\n"));
    

提交回复
热议问题