STL算法

作者: 上官宏竹 | 来源:发表于2022-11-05 09:54 被阅读0次

    sort

    并非所有容器都使用sort算法
    首先,关系型容器拥有自动排序功能,因为底层采用RB-Tree,所以不需要用到sort算法。
    其次,序列式容器中的stack、queue和priority-queue都有特定的出入口,不允许用户对元素排序。
    剩下的vector、deque,适用sort算法。

    transform

    std::transform在指定的范围内应用于给定的操作,并将结果存储在指定的另一个范围内。

    // 将字符转化为小写字符的函数对象
    class Lower
    {
    public:
        char operator()(char c_tmp)
        {
            if (c_tmp >= 'A' && c_tmp <= 'Z') {
                c_tmp = c_tmp - 'A' + 'a';
            }
            return c_tmp;
        }
    };
    
    string s_tmp("aBcdefG5556**@@4ddDDJL");
    string s_out_put;
    s_out_put.resize(s_tmp.size());
    transform(s_tmp.begin(), s_tmp.end(), s_out_put.begin(), Lower());
    

    for_each

      std::array<int, 10> arr = {1,2,3,4,5,6,7,8,9,0};
      std::for_each(arr.begin(), arr.end(), [](int &i){i++;});
      for(auto i : arr){std::cout << i << " ";}
    

    C++(标准库):35---STL算法之(for_each()算法)

    Lambda表达式

    Lambda表达式

    greater(greater_equal)和less(less_equal)

    头文件<functional>
    greater的实现:

    template <class T> struct greater {
      bool operator() (const T& x, const T& y) const {return x>y;}
      typedef T first_argument_type;
      typedef T second_argument_type;
      typedef bool result_type;
    };
    

    less的实现:

    template <class T> struct less {
      bool operator() (const T& x, const T& y) const {return x<y;}
      typedef T first_argument_type;
      typedef T second_argument_type;
      typedef bool result_type;
    };
    

    相关文章

      网友评论

          本文标题:STL算法

          本文链接:https://www.haomeiwen.com/subject/pucylltx.html