C ++如何动态创建2D向量 [英] C++ How to dynamically create a 2D vector

查看:61
本文介绍了C ++如何动态创建2D向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个n x n向量,以后可以将 作为表/矩阵使用.Xcode指向 for 循环中的 = ,并告诉我没有可行的重载'='.我不知道这意味着什么或如何解决.

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

也尝试过此操作,但Xcode也不喜欢它,这次指向并说 Expected')':

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

我的猜测是,这与我在 for 循环内声明新矢量 column 的方式有关.任何帮助/建议,我们将不胜感激.谢谢.

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.

推荐答案

尝试以下操作

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

int n = 5;
std::vector< std::vector<int> > row(n, std::vector<int>( n ) );

这篇关于C ++如何动态创建2D向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆