C++11 any_of, all_of, none_of

1. std::any_of

template <class InputIterator, class UnaryPredicate>
  bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);

Test if any element in range fulfills condition. 返回 [first, last) 范围内是否有任意元素满足条件。

Parameters
first, last

Input iterators to the initial and final positions in a sequence. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.

pred

Unary function that accepts an element in the range as argument and returns a value convertible to bool. The value returned indicates whether the element fulfills the condition checked by this function. pred 必须返回 bool 值。
The function shall not modify its argument.
This can either be a function pointer or a function object. pred 可以是一个函数指针或者是一个函数对象。(函数对象相关内容可点击 这里)

Return value

true if pred returns true for any of the elements in the range [first,last), and false otherwise.

If [first,last) is an empty range, the function returns false.

Example
// any_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::any_of
#include <array>        // std::array

int main () {
  std::array<int,7> foo = {0,1,-1,3,-3,5,-5};

  if (std::any_of(foo.begin(), foo.end(), [](int i){return i<0;}))
    std::cout << "There are negative elements in the range.\n";

  return 0;
}
实战题目

请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。

实现词典类 WordDictionary

  • WordDictionary() 初始化词典对象
  • void addWord(word)word 添加到数据结构中,之后可以对它进行匹配
  • bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 false 。word 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。
原文点击这里.
struct Trie {
    bool isEnd;
    vector<Trie *> children;

    Trie() : isEnd(false), children(26, nullptr) {};
};

class WordDictionary {
private:
    Trie *root;

    bool searchWord(string &word, int iStart, Trie *node) {
        for (int i = iStart; i < word.size(); ++i) {
            if (word[i] == '.') {
                return any_of(node->children.begin(), node->children.end(), [&](Trie *next) {
                    return next != nullptr && searchWord(word, i + 1, next);
                });
            } else if (!node->children[word[i] - 'a']) {
                return false;
            } else {
                node = node->children[word[i] - 'a'];
            }
        }
        return node->isEnd;
    }

public:
    WordDictionary() {
        root = new Trie();
    }

    void addWord(string word) {
        auto node = root;
        for (char ch:word) {
            if (!node->children[ch - 'a']) node->children[ch - 'a'] = new Trie();
            node = node->children[ch - 'a'];
        }
        node->isEnd = true;
    }

    bool search(string word) {
        return searchWord(word, 0, root);
    }
};

2. std::all_of

template <class InputIterator, class UnaryPredicate>
  bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);

Test condition on all elements in range. 返回 [first, last) 范围内是否所有元素都满足条件。

Example
// all_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::all_of
#include <array>        // std::array

int main () {
  std::array<int,8> foo = {3,5,7,11,13,17,19,23};

  if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )
    std::cout << "All the elements are odd numbers.\n";

  return 0;
}

3. std::none_of

template <class InputIterator, class UnaryPredicate>
  bool none_of (InputIterator first, InputIterator last, UnaryPredicate pred);

Test if no elements fulfill condition. 返回 [first, last) 范围内是否所有元素都不满足条件。

Example
// none_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::none_of
#include <array>        // std::array

int main () {
  std::array<int,8> foo = {1,2,4,8,16,32,64,128};

  if ( std::none_of(foo.begin(), foo.end(), [](int i){return i<0;}) )
    std::cout << "There are no negative elements in the range.\n";

  return 0;
}

4. function object

Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator() in their class, like for example:

struct myclass {
  int operator()(int a) {return a;}
} myobject;
int x = myobject (0);  // function-like syntax with object myobject 

They are typically used as arguments to functions, such as predicates or comparison functions passed to standard algorithms.

Example
// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

using namespace std;

bool myfunction(int i, int j) { return (i < j); }

struct myclass {
    bool operator()(int i, int j) { return (i < j); }
} myobject;

int main() {
    int myints[] = {32, 71, 12, 45, 26, 80, 53, 33};
    vector<int> myvector(myints, myints + 8); // 32 71 12 45 26 80 53 33

    // using default comparison (operator <):
    sort(myvector.begin(), myvector.begin() + 4); //(12 32 45 71) 26 80 53 33

    // using function as comp
    sort(myvector.begin() + 4, myvector.end(), myfunction); // 12 32 45 71 (26 33 53 80)

    // using object as comp
    sort(myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
    // sort (myvector.begin(), myvector.end(), myclass());  //  Another option

    // print out content:
    cout << "myvector contains:";
    for (int &it : myvector) cout << ' ' << it;

    return 0;
}

5. comparison function object type 和 function object 的区别

简单而言,对于下面这串代码 myclasscomparison function object typemyobject 或者 myclass()function object.

struct myclass {
    bool operator()(int i, int j) { return (i < j); }
} myobject;

在类型声明是使用的是 comparison function object type,如下面mappriority_queue类型声明代码所示。

// constructing maps
#include <iostream>
#include <map>

bool fncomp (char lhs, char rhs) {return lhs<rhs;}

struct classcomp {
  bool operator() (const char& lhs, const char& rhs) const
  {return lhs<rhs;}
};

int main ()
{
  std::map<char,int,classcomp> first; // class as Compare
  bool(*fn_pt)(char,char) = fncomp;
  std::map<char,int,bool(*)(char,char)> second (fn_pt); // function pointer as Compare

  return 0;
}
// constructing priority queues
#include <iostream>       // std::cout
#include <queue>          // std::priority_queue
#include <vector>         // std::vector
#include <functional>     // std::greater

struct mycomparison {
    bool operator()(const int &lhs, const int &rhs) const {
        return (lhs < rhs);
    }
};

int main() {
    int myints[] = {10, 60, 50, 20};

    std::priority_queue<int, std::vector<int>, std::greater<>> first(myints, myints + 4);
    std::priority_queue<int, std::vector<int>, mycomparison> second; // using mycomparison:

    return 0;
}

在函数中调用使用的是function object,如以下 none_of 代码所示。

// none_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::none_of
#include <array>        // std::array

int main () {
  std::array<int,8> foo = {1,2,4,8,16,32,64,128};

  if (std::none_of(foo.begin(), foo.end(), [](int i){return i<0;}))
    std::cout << "There are no negative elements in the range.\n";

  return 0;
}

参考资料

[1] C++ Reference

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值