通过使用索引将值分配给2D矢量 [英] Assigning values to 2D Vector by using indices
问题描述
我正在尝试通过使用两个索引将值添加到2D向量.当我运行程序时,我收到Windows消息,提示程序已停止运行.使用Dev-C ++进行调试表明存在分段错误(我不确定这是什么意思).请不要建议使用数组,我必须为此使用向量.
I am trying to add values to a 2D vector by using both indices. When I run my program, I get the windows message saying the program has stopped working. Using Dev-C++ to debug showed that there was a segmentation fault (I am not sure what this means). Please do not suggest using arrays, I have to use vectors for this assignment.
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
vector< vector<int> > matrix;
cout << "Filling matrix with test numbers.";
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
matrix[i][j] = 5; // causes program to stop working
}
}
}
我创建了一个测试用例,其中我想用值5填充3X3矩阵.我怀疑这与2D矢量的大小没有明确定义有关.如何通过使用索引用值填充2D向量?
I have created a test case where I want to fill a 3X3 matrix with the value 5. I suspect that it has something to do with the size of the 2D vector not being specifically defined. How would I fill a 2D vector with values by using the indices?
推荐答案
正如所写,这是有问题的,您正在尝试写入尚未分配内存的向量.
As written, this is problematic, you are trying to write to a vector for which you did not yet allocate memory.
选项1-提前调整向量大小
Option 1 - Resize your vectors ahead of time
vector< vector<int> > matrix;
cout << "Filling matrix with test numbers.";
matrix.resize(4); // resize top level vector
for (int i = 0; i < 4; i++)
{
matrix[i].resize(4); // resize each of the contained vectors
for (int j = 0; j < 4; j++)
{
matrix[i][j] = 5;
}
}
选项2-在声明矢量时调整其大小
Option 2 - Size your vector when you declare it
vector<vector<int>> matrix(4, vector<int>(4));
选项3-使用 push_back
调整矢量的大小.
Option 3 - Use push_back
to resize the vector as needed.
vector< vector<int> > matrix;
cout << "Filling matrix with test numbers.";
for (int i = 0; i < 4; i++)
{
vector<int> temp;
for (int j = 0; j < 4; j++)
{
temp.push_back(5);
}
matrix.push_back(temp);
}
这篇关于通过使用索引将值分配给2D矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!