How can I insert element into beginning of vector?

后端 未结 4 1534
天涯浪人
天涯浪人 2021-01-03 18:49

I need to insert values into the beginning of a std::vector and I need other values in this vector to be pushed to further positions for example: something adde

4条回答
  •  抹茶落季
    2021-01-03 19:19

    You can insert values to std::vector from back and then use std::reverse:

    Example:

    #include 
    #include 
    #include 
    
    void printVector( std::vector< int > const & _vector )
    {
        for( auto value : _vector )
        {
             std::cout << value << " ";
        }
    
        std::cout << std::endl;
    }
    
    int main()
    {
        std::vector< int > someVec;
        
        someVec.push_back( 5 );
        someVec.push_back( 4 );
        someVec.push_back( 3 );
        someVec.push_back( 2 );
        someVec.push_back( 1 );
    
        // (1)
        printVector( someVec );
    
        std::reverse( someVec.begin(), someVec.end() );
        
        // (2)
        printVector( someVec );
    
        return 0;
    }
    

    Output (1):

    5 4 3 2 1 
    

    Output (2):

    1 2 3 4 5 
    

提交回复
热议问题