可以使用std :: for_each()和std :: bind()在向量中过滤元素,然后将这些过滤元素放入新向量中
当我尝试使用std :: for_each()
and std :: bind()
时,为什么以下代码不起作用。向量并将这些过滤元素放入新的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;
}
此代码只能打印出两个是
。但是向量最终
中没有任何内容。
Why doesn't the below code work when I'm trying to use std::for_each()
and std::bind()
to filter elements in a vector
and put those filtered elements into a new 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;
}
This code can only print out two yes
. But nothing in the vector final
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最后,我知道发生了什么事。感谢@mikevine的帮助。
std :: bind()
将使用副本而不是参数的引用。因此,我们需要添加std :: Ref()
让它使用参考。Finally, I know what's happened. Thanks for the help from @MikeVine.
std::bind()
will use a copy rather than a reference of a parameter. So we need to addstd::ref()
to let it use a reference.