我写了这个程序,我需要传输一个 vector<vector<int>>
从一个类到一个函数来改变每个0
在 vector 中 1
.此功能有效,但在某处创建了 vector 的拷贝,并且元素仅更改为 0
在拷贝中,而不是在原始 vector 中。我该如何解决这个问题?
class Matrix {
friend istream& operator >> (istream &in, IntArr& a) {...}
friend ostream& operator << (ostream& out, Matrix& a) {...}
private:
vector < vector <int> > v;
int rows, cols;
public:
Matrix(int rows, int cols) {
this->rows = rows;
this->cols = cols;
v.resize(rows, vector<int>(cols));
}
// ...
vector < vector <int> > GetPointer() {
return v;
}
int GetRows() {
return rows;
}
int GetCols() {
return cols;
}
};
void IndividualTask(int rows, int cols, vector < vector <int> > v) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (v[i][j] == 0) {
v[i][j] = 1;
}
}
}
}
int main() {
Matrix arr1(2, 2);
cin >> arr1;
IndividualTask(arr1.GetRows(), arr1.GetCols(), arr1.GetPointer());
cout << arr1;
return 0;
}
最佳答案
您绝对需要先解决几个相关问题。 GetPointer
返回一个拷贝,IndividualTask
获取一个拷贝。您需要通过将 &
添加到类型以使其成为引用
首先,让 GetPointer
返回一个引用。
// right here---+
// |
// v
vector < vector <int> >& GetPointer() {
return v;
}
其次,让IndividualTask
引用
// and again here------+
// |
// v
void IndividualTask(int rows, int cols, vector < vector <int> >& v) {
// ...
}
这里有一个单独的问题,与 rows
和 cols
有关。 std::vector
已经知道它的大小,这不是 C,您不需要像这样传递数组大小。
您可以重写 GetRows
和 GetCols
(无论如何都应该是 const)以委托(delegate)给 vector 的大小,并且没有 Matrix
存储rows
和 cols
数据成员
int GetRows() const {
return v.size();
}
int GetCols() const {
// guard against the empty vector case
if (v.empty()) { return 0; }
// only correct if all rows have the same number of columns
return return v[0].size();
}
这不仅仅是方便,而且是正确的。如果有人通过执行 m.GetPointer().resize(N);
更改您的 v
的大小,您当前的 GetRows
和 GetCols
会出错!
您的函数也可以使用 vector 的这些特性,
void IndividualTask(vector < vector <int> >& v) {
for (std::size_t i = 0; i < v.size(); i++) {
for (std::size_t j = 0; j < v[i].size(); j++) {
if (v[i][j] == 0) {
v[i][j] = 1;
}
}
}
}
如果您使用的是 C++11
或 alter,则可以更轻松地使用范围 for 循环
void IndividualTask(vector < vector <int> >& v) {
for (auto& row : v) {
for (auto& e : row) {
if (e == 0) {
e = 1;
}
}
}
}
关于c++ - 如何在不复制的情况下将 vector 的 vector 从类传递到函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49590020/