How to implement 2D vector array?

后端 未结 9 656
你的背包
你的背包 2020-11-29 03:56

I\'m using the vector class in the STL library for the first time. How should I add to a specific row of the vector array?

struct x{
     vector 

        
相关标签:
9条回答
  • 2020-11-29 04:43

    Just use the following methods to create a 2-D vector.

    int rows, columns;        
    
    // . . .
    
    vector < vector < int > > Matrix(rows, vector< int >(columns,0));
    

    OR

    vector < vector < int > > Matrix;
    
    Matrix.assign(rows, vector < int >(columns, 0));
    
    //Do your stuff here...
    

    This will create a Matrix of size rows * columns and initializes it with zeros because we are passing a zero(0) as a second argument in the constructor i.e vector < int > (columns, 0).

    0 讨论(0)
  • 2020-11-29 04:44

    vector<int> adj[n]; // where n is number of rows in 2d vector.

    0 讨论(0)
  • 2020-11-29 04:45

    Another way to define a 2-d vector is to declare a vector of pair's.

     vector < pair<int,int> > v;
    
    **To insert values**
     cin >> x >>y;
     v.push_back(make_pair(x,y));
    
    **Retrieve Values**
     i=0 to size(v)
     x=v[i].first;
     y=v[i].second;
    

    For 3-d vectors take a look at tuple and make_tuple.

    0 讨论(0)
提交回复
热议问题