向量分配崩溃 [英] Vector assignment crashing
问题描述
vector< vector<int> > resizeVector(vector< vector<int> > m)
{
vector< vector<int> > newMatrix;
int i,j;
for (i = 0; i < m[i].size(); i++)
{
for(j = 0; j < m[j].size(); j++)
{
newMatrix[i][j] = m[i][j];
}
}
return (newMatrix);
}
我正在编写一个程序,它将执行很多矩阵操作,而本节崩溃了,我不知道为什么.我将其范围缩小:
I am making a program that will do a whole lot of matrix manipulation, and this section is crashing and I don't exactly know why. I have narrowed it down to the line:
newMatrix[i][j] = m[i][j];
它在这里崩溃了,我不确定为什么.
It crashes right here, and I am not sure why.
推荐答案
除了@Saurav发布的内容外,newMatrix
为空,因此您无法将值分配给newMatrix[i][j]
.您可以通过初始化给定大小的向量来解决此问题:
In addition to what @Saurav posted, newMatrix
is empty so you cannot assign values to newMatrix[i][j]
. You can fix this by initializing the vectors with a given size:
vector< vector<int> > resizeVector(vector< vector<int> > m)
{
vector< vector<int> > newMatrix(m.size());
int i,j;
for (i = 0; i < m.size(); i++)
{
newMatrix[i].resize(m[i].size());
for(j = 0; j < m[i].size(); j++)
{
newMatrix[i][j] = m[i][j];
}
}
return (newMatrix);
}
在for循环之前,我们将newMatrix
初始化为在其中包含m.size()
许多空向量(由于其默认构造函数,这些向量为空).在外部for循环的每次迭代过程中,我们都使用resize
成员函数确保newMatrix
中的每个向量具有正确的大小.
Before the for-loops we initialize newMatrix
to have m.size()
many empty vectors inside of it (the vectors are empty due to their default constructor). During each iteration of the outer for-loop we ensure that each vector within newMatrix
has the correct size using the resize
member function.
请注意,如果您想要向量的副本,则只需编写以下内容即可:
Note that if you want a copy of a vector you can simply just write:
vector< vector<int> > newMatrix(m);
这篇关于向量分配崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!