ITPub博客

首页 > 应用开发 > C/C++ > c++

c++

原创 C/C++ 作者:20170405 时间:2020-08-29 15:40:32 0 删除 编辑

  C++ 11 - std::any_of

  该算法与std::find_if相似,但不是返回满足条件的的序列中第一个元素的迭代器,而是如果任何元素满足条件后返回true,否则返回false。

  #include

  #include

  #include

  struct compare

  {

  int key;

  compare(int const &i): key(i) { }

  bool operator()(int const &i)

  {

  return (i == key);

  }

  };

  int main()

  {

  std::vectorv = { 4, 7, 5, 2, 6, 9 };

  int key = 6;

  if (std::any_of(v.begin(), v.end(), compare(key)))

  std::cout << "Element found";

  else

  std::cout << "Element not found";

  return 0;

  }

  或者直接修改find_of的案例:

  int main()

  {

  auto lst = {1,4,9,5,11};

  if(std::any_of(lst.begin(),lst.end(),[](int v){

  if(v%5 ==0)

  return true;

  else

  return false;

  })){

  std::cout << "Element found";

  }

  else{

  std::cout << "Element not found";

  }

  return 0;

  }

  C++ 11 - std::none_of

  该算法刚好和any_of相反,如果给定的条件在范围内所有元素都返回false,则返回true,如果至少一个元素返回true,则返回false。

  直接修改上述示例,将if条件改成“非”就可以了,不再 赘述。   郑州那个胎记医院好 http://www.zzzykdmlk.com/

  std::binary_search

  最后一种方法,如果vector是有序的,那么可以考虑使用这种算法,如果在给定范围内找到元素,则返回true,否则返回false。该方式是采用二分法查找,时间复杂度为O(log(n)),速度比较快。

  #include

  #include

  #include

  int main()

  {

  std::vectorv = { 1, 2, 3, 4, 5, 6, 7 };

  int key = 4;

  if (std::binary_search(v.begin(), v.end(), key))

  std::cout << "Element found";

  else

  std::cout << "Element not found";

  return 0;

  }


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69979119/viewspace-2715709/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2020-07-14

  • 博文量
    63
  • 访问量
    39785