【发布时间】:2015-02-20 00:50:10
【问题描述】:
我正在尝试检测向量的每个元素是否都满足给定条件,假设它必须是偶数。
#include <iostream>
#include <vector>
#include <algorithm>
bool isOdd(int i)
{
return i%2==0;
}
int main()
{
int arr[5]={1,2,3,4,5};
std::vector<int> myVec(arr, arr + sizeof(arr)/sizeof(arr[0]));
std::vector<int>::iterator it = std::find_if(myVec.begin(), myVec.end(),
isOdd());
// This piece of code is probably causing some problems;
while(myVec.empty()!=false) // while my vector IS NOT EMPTY
{
std::cout << *it << " "; // print out the value of elements that
// fullfiled the condition given in isOdd
}
return 0;
}
我的思维方式有什么问题? while 循环中的条件是错误的还是我完全错过了逻辑?
您能否向我提供一些关于这段代码有什么问题的复杂解释?
提前谢谢你。
附:我知道有可能改用 lambda 函数,但我不想太困惑:)
【问题讨论】:
-
find_if只返回满足条件的第一个迭代器 -
如果您使用的是 C++11,并且您不想打印出奇数,那么可以使用带有谓词的
std::all_of。