我对C ++很陌生,并且只使用STL容器创建了一个矩阵。我使用了向量(列)的向量(行)。我遇到的问题是在'write'操作中 - 我可能只使用基于迭代器的实现。问题很简单:它什么都不写。
我已经使用填充了不同值的矩阵进行了测试,虽然迭代器最终位于正确的位置,但它不会更改值。
这是我的代码:
void write(matrix mat, int row, int col, int input)
{
assert(row>=0 && col>=0);
assert(row<=mat.R && col<=mat.C);
//I set up the iterators.
vector<vector<int> >::iterator rowit;
vector<int>::iterator colit;
rowit = mat.rows.begin();
//I go to the row.
for(int i = 0; i<row-1; ++i)
{
++rowit;
}
colit = rowit->begin();
//I go to the column.
for(int j = 0; j<col-1; ++j)
{
++colit;
}
*colit = input; //Does nothing.
}
我在俯瞰什么? 感谢。
答案 0 :(得分:1)
matrix mat
是一个按值的参数,它复制矩阵,因此您正在写一个副本。
您应该通过引用传递矩阵,例如matrix & mat
。
但是等等...... 你每次都将矩阵作为第一个参数传递,这是一个不好的信号!
这通常表示该参数应该转换为可以运行方法的对象;这样,您根本不需要传递参数。因此,请改为创建Matrix
类。
所以,你可以这样做:
void write(matrix & mat, int row, int col, int input)
{
assert(row>=0 && col>=0);
assert(row<=mat.R && col<=mat.C);
mat[row][col] = input;
}