gpt4 book ai didi

c++ - “引用类型 const..”在索引 2d vector 时出现编译错误

转载 作者:行者123 更新时间:2023-11-30 03:22:26 33 4
gpt4 key购买 nike

<分区>

当我将元素推送到另一个 vector 内的 vector 时出现编译错误。

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.

我无法理解编译器试图表达的意思。我试过按值传递 vector 以及仅将代码放在 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]);
}
}

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com