您的位置:首页 > 编程语言 > C语言/C++

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: