How can I push_back data in a 2d vector of type int

前端 未结 6 876
借酒劲吻你
借酒劲吻你 2021-02-02 03:03

I have a vector and want to store int data in to it at run time can I store the data in a 2D vector in this manner ?

std::vector> n         


        
6条回答
  •  不思量自难忘°
    2021-02-02 03:20

    Here is one more approach.

    #include 
    #include 
    #include 
    #include 
    
    int main() 
    {
        std::vector > normal;
        normal.resize( 10, std::vector( 20 ) );
    
        for ( auto &v : normal ) std::iota( v.begin(), v.end(), 0 );
    
        for ( const auto &v : normal )
        {
            for ( int x : v ) std::cout << std::setw( 2 ) << x << ' ';
            std::cout << std::endl;
        }
    }
    

    The program output is

     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
    

    You can write a corresponding function

    #include 
    #include 
    #include 
    #include 
    
    template 
    T & init_2d( T &container, size_t m, size_t n )
    {
        container.resize( m, typename T::value_type( n ) );
    
        for ( auto &item : container ) std::iota( item.begin(), item.end(), 0 );
    
        return container;
    }
    
    int main() 
    {
        std::vector> v;
    
        for ( const auto &v : init_2d( v, 10, 20 ) )
        {
            for ( int x : v ) std::cout << std::setw( 2 ) << x << ' ';
            std::cout << std::endl;
        }
    
    }   
    

提交回复
热议问题