可以使用std :: for_each()和std :: bind()在向量中过滤元素,然后将这些过滤元素放入新向量中

发布于 2025-02-06 10:16:46 字数 707 浏览 1 评论 0原文

当我尝试使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

提笔书几行 2025-02-13 10:16:46

最后,我知道发生了什么事。感谢@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 add std::ref() to let it use a reference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文