C++ lambda algorithm
2015-11-26 22:30
471 查看
#include <algorithm> #include <vector> #include <string> #include <iostream> std::string make_plural(size_t ctr, const std::string &word, const std::string &ending) { return (ctr > 1) ? word + ending : word; } void elimDups(std::vector<std::string> &words) { std::sort(words.begin(), words.end()); auto end_unique = std::unique(words.begin(), words.end()); words.erase(end_unique, words.end()); } void biggies(std::vector<std::string> &words, std::vector<std::string>::size_type sz) { elimDups(words); std::stable_sort(words.begin(), words.end(), [](const std::string &left, const std::string &right) { return left.size() < right.size(); }); auto wc = std::find_if(words.begin(), words.end(), [sz](const std::string &s){ return s.size() >= sz; }); auto count = words.end() - wc; std::cout << count << make_plural(count, "word", "s") << " of length " << sz << " or longer" << std::endl; std::for_each(wc, words.end(), [](const std::string &s) { std::cout << s << " "; }); std::cout << std::endl; } int main() { std::vector<std::string> words; std::string str; while (std::cin >> str) { words.push_back(str); } biggies(words, 5); return 0; }
[1] C++ Primer 5th Section 10.3.2 Lambda Expressions (p. 391)
g++ xx.cpp -std=c++11
gcc 4.9.2
相关文章推荐
- C++指针与引用(三):引用使用注意事项
- C++中的Observer模式
- 对字符串中所有指定的子串进行替换
- C++ htons(), htonl(), ntohs(), ntohl()详解
- 【C语言】求带环单链表的环长
- 【C语言】找带环单链表的环入口
- C语言中三种常见排序算法分析
- 【C语言】判断单链表是否带环
- ubuntu安装lamp&&mysql中修改配置文件显示中文&&强大的vim配置&&c++连接Mysql
- 【C语言】删除任意一个节点n(不知道头结点,且所删节点既不是头结点也不是尾节点)
- c++11 async 的自带参数使用
- 顺序栈,C++基本实例应用
- C++内存分配原则方法
- c++11使用 async异步函数并传递参数以及auto的使用方法
- C++指针与引用(二):常用const指针,增强程序的健壮性
- C++设计模式[二十]策略模式
- 【程序设计基础_C语言】北理工的恶龙
- C语言基础第三篇--控制语句
- C++primer__泛型算法-泛型算法结构
- 浅谈C/C++的time_t函数