std::find_if_not的使用

来源:互联网 发布:gis数据挖掘前景 编辑:程序博客网 时间:2024/06/05 15:45

C++11

  1. // <algorithm>
  2. template <class InputIterator,
  3. class UnaryPredicate>
  4. InputIterator find_if_not (
  5. InputIterator first,
  6. InputIterator last,
  7. UnaryPredicate pred);

返回第一个值不满足给定条件的元素。

该函数等价于:

  1. template<class _InIt,
  2. class _Pr> inline
  3. _InIt _Find_if_not(_InIt _First, _InIt _Last, _Pr _Pred)
  4. { // find first element that satisfies !_Pred
  5. for (; _First != _Last; ++_First)
  6. if (!_Pred(*_First))
  7. break;
  8. return (_First);
  9. }
  • 参数及返回值

    firstlast

    分别指向一个序列中初始及末尾位置的输入迭代器。这个范围即 [first,last) ,包括 first 到 last 间的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。

    pred

    一元谓词(Unary)函数,以范围中的一个元素为参数,然后返回一个可转换成 bool 类型的值。

    其返回值表明指定元素是否满足当前函数所检测的条件。

    该函数不能修改其参数。

    可以是函数指针(Function pointer)类型或函数对象(Function object)类型。

    返回

    返回指向范围中使谓词函数返回 false 的第一个元素的迭代器。

    如果 pred 对所有元素返回 true,则返回 last 迭代器。

  • 代码示例

    例 1

    1. #include <iostream>
    2. #include <algorithm>
    3. #include <functional>
    4. #include <vector>
    5. // 用在此处是为了方便简洁, 在实际编程中慎用
    6. using namespace std;
    7. namespace ClassFoo{
    8. bool LessThan5(int & n) { return n < 5; }
    9. void FindIfNot_1() {
    10. int iarray[] = { 0, 1, 2, 3, 4, 5, 6, 4, 6, 7, 8 };
    11. vector<int> foo1(iarray, iarray + sizeof(iarray) / sizeof(int));
    12. //找出foo1中元素值不小于 5 的第一个元素,并打印其值
    13. cout << *find_if_not(foo1.begin(), foo1.end(), LessThan5) << endl;
    14. }
    15. }
    16. int main()
    17. {
    18. ClassFoo::FindIfNot_1();
    19. return 0;
    20. }

    5

    例 2

    C++11

    1. #include <iostream>
    2. #include <algorithm>
    3. #include <vector>
    4. #include <iterator>
    5.  
    6. namespace ClassFoo{
    7. void FindIfNot_2() {
    8. std::vector<int> v{ 0, 1, 2, 4, 7 };
    9. // 查找值不小于 5 元素
    10. auto it = std::find_if_not(std::begin(v), std::end(v), [](int &n) { return n < 5; });
    11. if (it != std::end(v)) {
    12. std::cout << "I find it: " << *it << '\n';
    13. }
    14. }
    15. }
    16. int main()
    17. {
    18. ClassFoo::FindIfNot_2();
    19. return 0;
    20. }

    I find it: 7

  • 扩展信息

    复杂度

    O(n)n 为 last first,对所有元素调用 pred,直到发现不匹配。

    数据争用相关

    访问在范围 [first,last) 中的部份(或所有)元素,且每个元素确定只被访问一次。

    异常安全性相关

    如果 pred 或操作某个迭代器抛异常,该函数才会抛异常。

    注意 无效参数将导致未定义行为(Undefined behavior)

0 0