all_of(vs2010版本)
- 引言
上一次写了一个快速排序,分别用自己写的和库中的算法的函数进行了实验,耗费时间真心不忍直视,故此决心学习直奔<algorithm>库。
- 作用
all_of 的作用就是测试容器中所有的元素是否符合某个条件,如果符合返回为 true,否则返回 false。当然这个条件是自己定义的。
- 实验
实验数据是10个2,测试所有的数据都是偶数。
- 代码(C++)
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;
// function declare
bool Condition( int i );
int main()
{
vector<int> v(10, 2);
cout << "Among the numbers: ";
copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
cout << '\n';
//if (all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; }))
if (all_of(v.begin(), v.end(), Condition))
{
cout << "All numbers are even\n";
}
system("pause");
return 0;
}
bool Condition( int i )
{
return i % 2 == 0;
}
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;
// function declare
bool Condition( int i );
int main()
{
vector<int> v(10, 2);
cout << "Among the numbers: ";
copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
cout << '\n';
//if (all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; }))
if (all_of(v.begin(), v.end(), Condition))
{
cout << "All numbers are even\n";
}
system("pause");
return 0;
}
bool Condition( int i )
{
return i % 2 == 0;
}