字段'谓词' CPP中的(find_if)函数中的(find_if)中的均值?
我是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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
std :: find_if
,但是每个呼叫只能找到一个元素(最多)。这意味着您需要一个循环。第一次,您从v.begin()
开始。这将返回第一个偶数元素的迭代器。要查找第二个偶数元素,您必须启动第二个find_if
而不是v.begin()
,而是 () +1
)第一个找到的元素。您应该尽快停止,
std :: find_if
返回v.end()
,它甚至可以在第一个呼叫上(如果所有元素都是奇数)。 IEfor(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 atv.begin()
. This will return the iterator of the first even element. To find the second even element, you have to start the secondfind_if
search not atv.begin()
, but after (+1
) the first found element.You should stop as soon as
std::find_if
returnsv.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))