钜形不锈钢水箱 发表于 2023-5-30 11:34:38

c++11: all_of 、 any_of 和 none_of


[*]有效的字母异位词
class Solution {
public:
    bool isAnagram(string s, string t) {
      if(s.size()!=t.size())
            return false;
      int ans={0};
      for(auto& ch:s){
            ++ans;
      }
      for(auto& ch:t){
            --ans;
      }
      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表达式)。然后算法会对整个序列中的每个元素调用该函数对象,并根据返回值判断序列是否满足条件。
这些算法对检查序列中元素很有用,可以使代码更加简洁明了。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: c++11: all_of 、 any_of 和 none_of