当我尝试使用 std::for_each()
和 std::bind()
来过滤 a 中的元素时,为什么下面的代码不起作用 vector
并将这些过滤后的元素放入新的 vector
中?
void mypred(int a, int b, vector<int>& c){
if(a < b){
cout <<"yes" << endl;
c.push_back(a);
}
}
int main(){
vector<int> test = {1,2,3,4,5,6,7};
vector<int> final;
final.reserve(10);
for_each(test.begin(), test.end(), bind(mypred, placeholders::_1, 3, final));
for(auto i = final.begin(); i != final.end(); i++){
cout << *i << endl;
}
return 0;
}
这段代码只能打印出两个yes
。但 vector final
中没有任何内容。
最佳答案
我终于知道发生了什么了。感谢@MikeVine 的帮助。
std::bind()
将使用参数的拷贝而不是引用。所以我们需要添加 std::ref()
让它使用引用。
关于c++ - 无法使用 std::for_each() 和 std::bind() 过滤 vector 中的元素并将这些过滤后的元素放入新 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72577547/