本文介绍了矢量分配崩溃,不知道为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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循环的每次迭代期间,我们确保 newMatrix 中的每个向量使用 resize 成员具有正确的大小

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

这篇关于矢量分配崩溃,不知道为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-08 18:04