C++

20170405發表於2020-08-29

  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條件改成“非”就可以了,不再 贅述。  

  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部落格 ” ,連結:http://blog.itpub.net/69979119/viewspace-2715709/,如需轉載,請註明出處,否則將追究法律責任。