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

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

I have next code:

#include 
#include 
#include 
#include 

//namespace std
//{

std::ostream&         


        
10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 21:04

    There is no standard way to cout a std::pair because, well, how you want it printed is probably different from the way the next guy wants it. This is a good use case for a custom functor or a lambda function. You can then pass that as an argument to std::for_each to do the work.

    typedef std::map MyMap;
    
    template 
    struct PrintMyMap : public std::unary_function
    {
        std::ostream& os;
        PrintMyMap(std::ostream& strm) : os(strm) {}
    
        void operator()(const T& elem) const
        {
            os << elem.first << ", " << elem.second << "\n";
        }
    }
    

    To call this functor from your code:

    std::for_each(some_map.begin(),
                  some_map.end(),
                  PrintMyMap(std::cout));
    

提交回复
热议问题