3

我有一个 MatrixGraph 类,其成员变量 M 的类型为vector<vector<double> >。我有一个构造函数,它接受一个无符号的,并从该输入生成一个 NxN 矩阵,我想将它初始化为零。问题是当我运行我的代码时,调试器会在我尝试分配东西时启动。我试过方法,第一个:

MatrixGraph::MatrixGraph(unsigned num_nodes) {
for(int i = 0;i < num_nodes;i++) {
    for(int j = 0;j < num_nodes;j++) {
        M[i][j] = 0.0;//breaks on this line
    }//end i for loop
}//end j for loop
}

我尝试的第二种方法是在这里找到的,但这也不起作用:

MatrixGraph::MatrixGraph(unsigned num_nodes) {
for(int i = 0;i < num_nodes;i++) {
        M[i].resize(num_nodes);//breaks on this line
    }
}

我在这里评论了调用堆栈的最后一行在我得到错误之前的位置。调用堆栈上的下一行显示了类向量,并说我的 Pos 大于我的向量的大小。我假设这是一个大小为零的矩阵,但我不知道为什么我不能让它更大。有什么建议么?

谢谢!

4

2 回答 2

3

The reason your code is failing is that you cant use the [] operation on a vector before that element exists. The usual way to add a value to a vector is to use push_back.

If you want to initialize to 0 you want assign(). Resize the outer vector to the required size and then assign each of the inner vectors with 0

M.resize(num_nodes);
for(int i = 0;i < num_nodes;i++) 
{        
    M[i].assign(num_nodes,0.0f);
}//end i for loop

This can also be done. It is cleaner code but a tad less efficient since it makes 1 extra vector object.

vector<double> temp;
temp.assign(num_nodes,0.0);
M.assign(num_nodes,temp);

or just

M.assign(num_nodes,vector<double>(num_nodes,0.0));

neatest one(courtesy @Mike Seymour) would be

MatrixGraph(unsigned num_nodes) 
   : M(num_nodes, vector<double>(num_nodes,0.0)) 
{}

(thanks Mike Seymour for the constructor syntax)

What you are doing here is initializing the outer vector with a temp vector full of 0.0s

于 2012-11-16T02:28:49.250 回答
2

您需要用数据填充向量 M:M.resize(num_nodes)

这应该这样做:

MatrixGraph::MatrixGraph(unsigned num_nodes) 
{
    M.resize(num_nodes);
    for(int i = 0;i < num_nodes;i++) 
    {
        M[i].resize(num_nodes);
        for(int j = 0;j < num_nodes;j++) 
        {
            M[i][j] = 0.0;
        }//end j for loop
    }//end i for loop
}
于 2012-11-16T02:24:36.387 回答