C++ How to dynamically create a 2D vector

前端 未结 3 2003
陌清茗
陌清茗 2021-01-27 00:14

I\'m trying to create an n x n vector that I can later cout as a table/matrix. Xcode points to the = in the for loop and tells me No

相关标签:
3条回答
  • 2021-01-27 01:00

    When the constructor of row is called, all elements are initialized too. I think this code does what you're looking to do:

    for (int i=0; i<n; i++) {
        row[i].resize(n);
    }
    

    Now all elements of row will be of size n.

    0 讨论(0)
  • 2021-01-27 01:07

    Try the following

    int n = 5;
    std::vector< std::vector<int> > row(n);
    for (int i=0; i<n; i++) {
       row[i].push_back( std::vector<int>(n) );
    }
    

    or

    int n = 5;
    std::vector< std::vector<int> > row(n, std::vector<int>( n ) );
    
    0 讨论(0)
  • 2021-01-27 01:09

    The simple solution is to use the relevant constructor of std::vector, initializing it to n elements each having the value of val - no loops necessary.

    std::vector<T> (n, val);
    

    Having your original snippet we would end up with the following, which will initialize row to have n std::vectors, each of which having n elements.

    std::vector<std::vector<int> > row (n, std::vector<int> (n));
    
    0 讨论(0)
提交回复
热议问题