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

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

I have next code:

#include 
#include 
#include 
#include 

//namespace std
//{

std::ostream&         


        
10条回答
  •  温柔的废话
    2020-12-04 20:52

    I've founded one new elegant way to solve this problem.
    I've got many interest ideas when read answers:

    • wrap iterator, for transform std::pair to std::string;
    • wrap std::pair, for have a chance to overload operator<<(...);
    • use usual std::for_each with printing functor;
    • use std::for_each with boost::labda - looks nice, except accessing to std::pair< >::first and std::pair< >::second members;

    I think I will use all of this ideas in future for solve different other problems.
    But for this case I've understaded that I can formulate my bproblem as "transform map's data to strings and write them to output stream" instead "copy map's data to ouput stream". My solution looks like:

    namespace
    {
    std::string toString( const std::pair< size_t, size_t >& data)
    {
        std::ostringstream str;
        str << data.first << ", " << data.second;
        return str.str();
    }
    } // namespace anonymous
    
    std::transform( 
        some_map.begin(), 
        some_map.end(), 
        std::ostream_iterator< std::string >( std::cout, "\n" ),
        toString );
    

    I think this method is most short and expressive than others.

提交回复
热议问题