• 删除容器中重复字符串并按长度排序…


    #include < iostream> >
    #include < algorithm> >
    #include < string> >
    #include < vector> >

    using namespace std;

    string make_plural(size_t ctr, const string &word,
        const string &ending)
    {
        return (ctr > 1) ? word + ending : word;
    }

    bool IsShorter(const string &str1, const string &str2)
    {
        return str1.size() < str2.size();
    }

    void ElimDups(vector &words)
    {
        sort(words.begin(), words.end());

        auto end_unique = unique(words.begin(), words.end());
        words.erase(end_unique, words.end());
    }

    void BiggiesWithFind_if(vector &words,
        vector::size_type sz)
    {
        //按字典排序, 删除重复单词
        ElimDups(words);

        //按长度排序, 长度相同的维持字典序
        stable_sort(words.begin(), words.end(),
            [](const string &str1, const string &str2)
        {return str1.size() < str2.size(); });

        //获取一个迭代器, 指向第一个满足size() > sz的元素
        auto wc = find_if(words.begin(), words.end(),
            [=](const string &s)//可以使用隐式捕获, 编译器会自己推断捕获内容
                                //捕获引用使用'&' , 捕获值使用'='
        {return s.size() >= sz;    });

        //计算满足条件元素的数目
        auto count = words.end() - wc;
        cout << count << " " << make_plural(count, "word", "s")
            << "  of length  " << sz << "  or longer" << endl;

        //打印每个长度大于等于要求的值的单词, 每个单词后面接一个空格
        for_each(wc, words.end(),
            [](const string &s) {cout << s << " "; });
        cout << endl;
    }

    void BiggiesWithPartition(vector &words,
        vector::size_type sz)
    {
        ElimDups(words);
        auto wc = partition(words.begin(), words.end(),
            [sz](const string &str) {return str.size() < sz; });
        //计算满足条件元素的数目
        auto count = words.end() - wc;
        cout << count << " " << make_plural(count, "word", "s")
            << "  of length  " << sz << "  or longer" << endl;

        //打印每个长度大于等于要求的值的单词, 每个单词后面接一个空格
        for_each(wc, words.end(),
            [](const string &s) {cout << s << " "; });
        cout << endl;
    }

    int main(int argc, char **argv)
    {
        vectorstr_vec{ "the", "red", "fox", "jump", "over", "the", "slow", "red", "turtle" };
        BiggiesWithFind_if(str_vec, 4);
        cout << "-------------------" << endl;
        BiggiesWithPartition(str_vec, 4);
        return 0;
    }

  • 相关阅读:
    基于ZYNQ XC7Z045 FFG 900的高性能计算模块
    linux TCP数据包封装在SKB的过程分析
    关于 linux中TCP数据包(SKB)序列号的小笔记
    TCP的TIME_WAIT状态
    Linux-2.6.25 TCPIP函数调用大致流程
    Linux 下不经过BIOS重启(i386)
    Linux块设备加密之dm-crypt分析
    Device Mapper 代码分析
    Linux 下的一个全新的性能测量和调式诊断工具 Systemtap, 第 3 部分: Systemtap
    Linux 下的一个全新的性能测量和调式诊断工具 Systemtap, 第 2 部分: DTrace
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4098745.html
Copyright © 2020-2023  润新知