索引二维向量时“引用类型为const ..”的编译错误

时间:2018-07-03 09:48:21

标签: c++

将元素推到另一个向量内的向量时,出现编译错误。

void addElem(vector<vector<int> >& subsets, int elem){
    int smallerSubsetSize = subsets.size();
    for(int i = 0; i < smallerSubsetSize; i++){
       vector<int> originalSubset = subsets[i];
       subsets.push_back(originalSubset.push_back(elem));
    }
    vector<int> uniset;
    uniset.push_back(elem);
    subsets.push_back(uniset);
}

我遇到以下错误:

powerset.cpp:11:27: error: reference to type 'const
  std::__1::__vector_base<std::__1::vector<int, std::__1::allocator<int> >,
  std::__1::allocator<std::__1::vector<int, std::__1::allocator<int> > >
  >::value_type' (aka 'const std::__1::vector<int, std::__1::allocator<int> >')
  could not bind to an rvalue of type 'void'
    subsets.push_back(originalSubset.push_back(elem));
                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/vector:688:62: note: passing
  argument to parameter '__x' here
_LIBCPP_INLINE_VISIBILITY void push_back(const_reference __x);
                                                         ^
1 error generated.

我无法理解编译器要说的内容。我尝试过按值传递向量,以及仅将代码放入main中。

如果重要的话,这是我的完整代码:

// CtCI 8.4
#include <iostream>
#include <vector>

using namespace std;

void addElem(vector<vector<int> >& subsets, int elem){
    int smallerSubsetSize = subsets.size();
    for(int i = 0; i < smallerSubsetSize; i++){
        vector<int> originalSubset = subsets[i];
        subsets.push_back(originalSubset.push_back(elem));
    }
    vector<int> uniset;
    uniset.push_back(elem);
    subsets.push_back(uniset);
}

void printVector(const vector<int> &v){
    for(int i = 0; i < v.size(); i++){
        cout << v[i] << " ";
    }
    cout << endl;
}

int main(){
    // set size
    int n;
    cin >> n;
    vector<int> set(n);
    for(int i = 0; i < n; i++){
       cin >> set[i];
     }

    vector<vector<int> > subsets;
    for(int i = 0; i < set.size(); i++){
        addElem(subsets, set[i]);
    }
    // print subsets
    for(int i = 0; i < subsets.size(); i++){
        printVector(subsets[i]);
    }
}

1 个答案:

答案 0 :(得分:2)

void addElem(vector<vector<int> >& subsets, int elem){

    int smallerSubsetSize = subsets.size();
    vector<int> originalSubset;
    for(int i = 0; i < smallerSubsetSize; i++)
    {
       originalSubset = subsets[i];
       originalSubset.push_back(elem);
       subsets.push_back(originalSubset); 
       /*by doing this, we are passing vectortype as argument to push_back(),
         do not pass argument in push_back() as void,   
         as originalSubset.push_back(elem) return void as return type */
    } 
    vector<int> uniset;
    uniset.push_back(elem);
    subsets.push_back(uniset);
}

参考:http://www.cplusplus.com/reference/vector/vector/push_back/