std::istream_iterator<> with copy_n() and friends

前端 未结 4 1960
臣服心动
臣服心动 2020-12-05 13:59

The snippet below reads three integers from std::cin; it writes two into numbers and discards the third:

std::vector num         


        
4条回答
  •  生来不讨喜
    2020-12-05 14:31

    Today I encountered very similar problem, and here is the example:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    struct A
    {
        float a[3];
        unsigned short int b[6];
    };
    
    void ParseLine( const std::string & line, A & a )
    {
        std::stringstream ss( line );
    
        std::copy_n( std::istream_iterator( ss ), 3, a.a );
        std::copy_n( std::istream_iterator( ss ), 6, a.b );
    }
    
    void PrintValues( const A & a )
    {
        for ( int i =0;i<3;++i)
        {
            std::cout<

    Compiling the above example with g++ 4.6.3 produces one:

    1.1 2.2 3.3 7 6 3 2 1 1
    

    , and compiling with g++ 4.7.2 produces another result :

    1.1 2.2 3.3 8 7 6 3 2 1
    

    The c++11 standard tells this about copy_n :

    template
    OutputIterator copy_n(InputIterator first, Size n, OutputIterator result);
    

    Effects: For each non-negative integer i < n, performs *(result + i) = *(first + i).
    Returns: result + n.
    Complexity: Exactly n assignments.

    As you can see, it is not specified what exactly happens with the iterators, which means it is implementation dependent.

    My opinion is that your example should not read the 3rd value, which means this is a small flaw in the standard that they haven't specified the behavior.

提交回复
热议问题