字段'谓词' CPP中的(find_if)函数中的(find_if)中的均值?

发布于 2025-02-11 02:27:42 字数 601 浏览 1 评论 0原文

我是C ++的初学者。我正在学习STL,尤其是向量&迭代器使用..我试图使用(find_if)函数在屏幕上显示均匀的数字。我知道我必须将布尔值返回到函数中的第三个字段(find_if)..但它为我提供了我的所有元素向量!!! 。 这是我的代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool EvenNumber(int i)
{
        return i%2==0
}
/*bool GreaterThanThree(int s)
{
  return s>3;
}
*/
int main()
{
    vector <int> v={2,1,4,5,0,3,6,7,8,10,9};
    sort(v.begin(),v.end());
     auto it= find_if(v.begin(),v.end(),EvenNumber);
     for(;it!=v.end();it++)
     {
         cout<<*it<<" ";
     }
    return 0;
}

I'm a beginner in c++. I was learning STL especially vectors & iterators uses..I was trying to use (find_if) function to display even numbers on the screen.I knew that I have to return boolean value to the third field in the function(find_if) ..but it gives me all elements in the vector !!! .but,When I used the function (GreaterThanThree) the code outputs the right values without any problem.
this is my code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool EvenNumber(int i)
{
        return i%2==0
}
/*bool GreaterThanThree(int s)
{
  return s>3;
}
*/
int main()
{
    vector <int> v={2,1,4,5,0,3,6,7,8,10,9};
    sort(v.begin(),v.end());
     auto it= find_if(v.begin(),v.end(),EvenNumber);
     for(;it!=v.end();it++)
     {
         cout<<*it<<" ";
     }
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

明天过后 2025-02-18 02:27:42

您可以使用std :: find_if,但是每个呼叫只能找到一个元素(最多)。这意味着您需要一个循环。第一次,您从v.begin()开始。这将返回第一个偶数元素的迭代器。要查找第二个偶数元素,您必须启动第二个find_if而不是v.begin(),而是 ) +1)第一个找到的元素。

您应该尽快停止,std :: find_if返回v.end(),它甚至可以在第一个呼叫上(如果所有元素都是奇数)。 IE for(auto it = std :: find_if(v.begin(),v.end(),evenumber); it!= v.end(); it = std :: find_if(it+1,v,v .end(); evennumer)

You can use std::find_if, but each call finds only one element (at best). That means you need a loop. The first time, you start at v.begin(). This will return the iterator of the first even element. To find the second even element, you have to start the second find_if search not at v.begin(), but after (+1) the first found element.

You should stop as soon as std::find_if returns v.end(), which could even be on the first call (if all elements are odd). I.e. for(auto it = std::find_if(v.begin(), v.end(), EvenNumber); it != v.end(); it = std::find_if(it+1, v.end(); EvenNumer))

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