C++11新增的一些便利的算法

发表于:2014-9-10 10:44

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:qicosmos    来源:51Testing软件测试网采编

  c++11新增加了一些便利的算法,这些新增的算法使我们的代码写起来更简洁方便,这里仅仅列举一些常用的新增算法,算是做个总结,更多的新增算法读者可以参考http://en.cppreference.com/w/cpp/algorithm。
  算法库新增了三个用于判断的算法all_of、any_of和none_of:
  template< class InputIt, class UnaryPredicate >
  bool all_of( InputIt first, InputIt last, UnaryPredicate p );
  template< class InputIt, class UnaryPredicate >
  bool any_of( InputIt first, InputIt last, UnaryPredicate p );
  template< class InputIt, class UnaryPredicate >
  bool none_of( InputIt first, InputIt last, UnaryPredicate p );
  all_of:检查区间[first, last)中是否所有的元素都满足一元判断式p,所有的元素都满足条件返回true,否则返回false。
  any_of:检查区间[first, last)中是否至少有一个元素都满足一元判断式p,只要有一个元素满足条件就返回true,否则返回true。
  none_of:检查区间[first, last)中是否所有的元素都不满足一元判断式p,所有的元素都不满足条件返回true,否则返回false。
  下面是这几个算法的示例:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> v = { 1, 3, 5, 7, 9 };
auto isEven = [](int i){return i % 2 != 0;
bool isallOdd = std::all_of(v.begin(), v.end(), isEven);
if (isallOdd)
cout << "all is odd" << endl;
bool isNoneEven = std::none_of(v.begin(), v.end(), isEven);
if (isNoneEven)
cout << "none is even" << endl;
vector<int> v1 = { 1, 3, 5, 7, 8, 9 };
bool anyof = std::any_of(v1.begin(), v1.end(), isEven);
if (anyof)
cout << "at least one is even" << endl;
}
  输出:
  all is odd
  none is odd
  at least one is even
  算法库的查找算法新增了一个find_if_not,它的含义和find_if是相反的,即查找不符合某个条件的元素,find_if也可以实现find_if_not的功能,只需要将判断式改为否定的判断式即可,现在新增了find_if_not之后,就不需要再写否定的判断式了,可读性也变得更好。下面是它的基本用法:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> v = { 1, 3, 5, 7, 9,4 };
auto isEven = [](int i){return i % 2 == 0;};
auto firstEven = std::find_if(v.begin(), v.end(), isEven);
if (firstEven!=v.end())
cout << "the first even is " <<* firstEven << endl;
//用find_if来查找奇数则需要重新写一个否定含义的判断式
auto isNotEven = [](int i){return i % 2 != 0;};
auto firstOdd = std::find_if(v.begin(), v.end(),isNotEven);
if (firstOdd!=v.end())
cout << "the first odd is " <<* firstOdd << endl;
//用find_if_not来查找奇数则无需新定义判断式
auto odd = std::find_if_not(v.begin(), v.end(), isEven);
if (odd!=v.end())
cout << "the first odd is " <<* odd << endl;
}
  将输出:
  the first even is 4
  the first odd is 1
  the first odd is 1
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号