如何在不复制的情况下将矢量矢量从一个类传递给另一个函数?

时间:2018-03-31 16:31:57

标签: c++ vector stl

我编写了这个程序,我需要将vector<vector<int>>从类转移到函数,以将向量中的每个0更改为1。此函数有效,但某处创建了矢量副本,并且元素仅在副本中更改为0,而不是在原始矢量中。我该如何解决这个问题?

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

1 个答案:

答案 0 :(得分:2)

您首先需要解决几个相关问题。 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) {
   // ...
}

这里有一个单独的问题,rowscolsstd::vector已经知道它的大小,这不是C,你不需要像这样传递数组大小。

你可以重写GetRowsGetCols(无论如何应该是const)来委托矢量的大小,而不是Matrix存储rows和{{1数据成员

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(); } 来改变v的大小,那么您当前的m.GetPointer().resize(N);GetRows就会出错!

你的功能也可以使用矢量的这些特性,

GetCols

如果您使用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; } } } } 或更改,则可以更轻松地使用ranged for循环

C++11
相关问题