0

find 和 find_if, find_if_not

 2 years ago
source link: https://charon-cheung.github.io/2022/05/18/C++/C++%20%20%E6%A8%A1%E6%9D%BF%E4%B8%8ESTL/find%20%E5%92%8C%20find_if,%20find_if_not/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

find 和 find_if, find_if_not

find 和 find_if, find_if_not
2022-05-18|C++C++ 模板与STL|
Word count: 266|Reading time: 1 min

头文件: #include <algorithm>

返回范围 [first, last) 中满足特定判别标准的首个元素:

  • find: 搜索等于 value 的元素

  • find_if: 根据指定的查找规则,在指定区域内查找第一个符合该函数要求(使函数返回 true)的元素。如果查找成功,该迭代器指向的是查找到的那个元素;反之,如果查找失败,该迭代器的指向和 last 迭代器相同

  • find_if_not: 与find_if相反

示例代码:

std::vector<int> score{ 10, 20, 30, 40 };

auto it_1 = std::find(score.begin(), score.end(), 30 );
if(it_1 != score.end() )
qDebug()<< "found !";
else qDebug()<< "no found !";

auto it_2 = std::find_if(score.begin(), score.end(), [](int& m){return m>20;} );
if(it_2 != score.end() )
qDebug()<< "found: " << *it_2;
else qDebug()<< "no found !";
  • 若作为算法一部分调用的函数的执行抛出异常,且 ExecutionPolicy 为标准策略之一,则调用 std::terminate 。对于任何其他 ExecutionPolicy ,行为是实现定义的。
  • 若算法无法分配内存,则抛出 std::bad_alloc

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK