C++ How to dynamically create a 2D vector

家住魔仙堡 提交于 2020-01-30 08:57:05

问题


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 viable overloaded '='. I don't know what that means or how to fix it.

int n=5;
vector< vector<int> > row(n);
for (int i=0; i<n; i++) {
   row[i] = new vector<int> column(n);
}

Also tried this, but Xcode didn't like it either and this time pointed to column and said Expected ')' :

int n=5;
vector< vector<int> > row;
for (int i=0; i<n; i++) {
   row.push_back(new vector<int> column(n));
}

My guess is that it has something to do with the way I'm declaring the new vector column inside the for loop. Any help/advice is much appreciated. Thanks.


回答1:


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 ) );



回答2:


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));



回答3:


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.



来源:https://stackoverflow.com/questions/29072961/c-how-to-dynamically-create-a-2d-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!