【发布时间】:2018-07-21 20:05:28
【问题描述】:
我 for_each 一个向量并在 for 循环中更改了向量。但是,当我运行程序时,在程序离开 for 循环后,向量仍然没有改变。是什么导致了问题?如果我仍然想使用 for_each 循环,我该如何解决?
这是代码(我对leetcode 78的解决方案):
class Solution {
public:
void print(vector<int> t){
for(int a:t){
cout<<a<<" ";
}
cout<<endl;
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
res.push_back(vector<int>{});
int m=nums.size();
for(int a:nums){
cout<<"processing "<<a<<endl;
for(auto t:res){
vector<int> temp{a};
temp.insert(temp.end(),t.begin(), t.end());
res.push_back(temp);
cout<<"temp is ";
print(temp);
res.reserve();
}
// int s=res.size();
// for(int i=0;i<s;i++){
// vector<int> temp{a};
// temp.insert(temp.end(), res[i].begin(), res[i].end());
// res.push_back(temp);
// }
}
return res;
}
};
如果我使用我注释掉的地方来替换 for_each 循环,它给出了正确的解决方案。
【问题讨论】:
-
也许把它变成一个minimal reproducible example 有一些输入、预期输出以及你的输出有何不同。
-
对正在迭代的容器进行变异可能会有问题,因为某些类型的变异会使迭代器无效(这是不好的)。
-
你确定这是你的真实代码吗?
res.reserve();行无法编译。