设为首页 加入收藏

TOP

c++11: all_of 、 any_of 和 none_of
2023-07-23 13:29:22 】 浏览:31
Tags:11: all_of any_of none_of
  1. 有效的字母异位词
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size()!=t.size())
            return false;
        int ans[26]={0};
        for(auto& ch:s){
            ++ans[ch-'a'];
        }
        for(auto& ch:t){
            --ans[ch-'a'];
        }
        return all_of(ans,ans+26,[](int i){return i==0;});
    }
};

C++11 中提供了一些用于检查序列中元素的算法,包括:

  • all_of: 检查序列中是否所有元素都满足某个条件。

  • any_of: 检查序列中是否存在至少一个元素满足某个条件。

  • none_of: 检查序列中是否不存在任何一个元素满足某个条件。
    这些算法的使用方式如下:

    #include <algorithm>
    #include <array>
    
    int main() {
        std::array<int, 5> arr {1, 2, 3, 4, 5};
    
        // 检查数组中是否所有元素都大于0
        bool all_greater_than_zero = std::all_of(arr.begin(), arr.end(), [](int i) {return i > 0;}); 
        // true
        
        // 检查数组中是否存在大于3的元素
        bool any_greater_than_three = std::any_of(arr.begin(), arr.end(), [](int i) {return i > 3;});
        // true
        
        // 检查数组中是否不存在大于10的元素
        bool none_greater_than_ten = std::none_of(arr.begin(), arr.end(), [](int i) {return i > 10;});
        // true
    
    }
    

    这些算法使用,只需要传入序列的首尾迭代器和一个用于检查条件的函数对象(上例使用了lambda表达式)。然后算法会对整个序列中的每个元素调用该函数对象,并根据返回值判断序列是否满足条件。
    这些算法对检查序列中元素很有用,可以使代码更加简洁明了。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇驱动开发:内核解析PE结构导出表 下一篇C++面试八股文:如何在堆上和栈上..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目