【问题标题】:Passing 2D vector by reference通过引用传递 2D 矢量
【发布时间】:2014-03-15 04:12:42
【问题描述】:

好久没接触c++了,刚刚在通过引用传递二维向量时遇到了一个很奇怪的问题,在main函数中有描述:

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {


    vector<vector<int> > result;
    //I intentionally omit the codes for permutation,
    //only pushing the original one to the result
    result.push_back(num);

    return result;


    }

    //print the permutation, I want to pass by referrence
    void printPerm(vector<vector<int> >  &result) {

    for(int i=0; i<result.size(); i++) {

        for(int j=0; j<result[i].size(); j++) {

            cout << result[i][j]<<" ";
            }
        }

    }

};

int main() {

    vector<int> old;
    old.push_back(1);
    old.push_back(2);
    old.push_back(3);

    Solution sol;

    //this gives me error for no matching function
    //call, candidate argument doesn't match
    sol.printPerm((sol.permute(old))); 

    //but the one below works!

    vector<vector<int> > result = sol.permute(old);

    sol.printPerm(result);


}

【问题讨论】:

  • 如果可以使用c++11,可以使用新的en.cppreference.com/w/cpp/language/range-for
  • 请注意,这与向量(或任何特定类型)无关;它只与返回值和引用有关。请参阅codepad.org/4PNCcGs5 了解具有完全相同问题的更简单的程序。
  • @delnan 是的,我不知道是什么原因造成的,所以我决定发布整个内容...

标签: c++ vector reference


【解决方案1】:

您需要在结果中添加const 以允许绑定到右值

 void printPerm(const vector<vector<int> >  &result) 
 //             ^^^^^^

【讨论】:

  • 谢谢!但是如果printPerm 想要修改结果呢?
  • @Arch1tect:在这种情况下,您不会传递函数的返回值。
  • @VaughnCato 你的意思是我不能吗?那么在那种情况下,我必须分两步完成?我的意思是两行代码。
  • @Arch1tect:如果函数要修改参数,那么您可能想要修改的结果。如果您只是传递另一个函数的结果而不是传递变量,那么您将无法看到参数的更改。
  • @VaughnCato 好吧...谢谢。虽然我还是觉得这个设计不太灵活也不方便..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
相关资源
最近更新 更多