【C++ Primer | 07】泛型算法

 定制操作

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <algorithm>
 5 #include <numeric>
 6 #include <list>
 7 using namespace std;
 8 
 9 template <typename Sequence>
10 inline ostream& println(Sequence const& seq)
11 {
12     for (auto const& elem : seq)
13         cout << elem << " ";
14     cout << endl;
15     return cout;
16 }
17 
18 inline bool is_shorter(std::string const& lhs, std::string const& rhs)
19 {
20     return  lhs.size() < rhs.size();
21 }
22 
23 void elimdups(vector<string> &vs)
24 {
25     sort(vs.begin(), vs.end());
26     auto new_end = unique(vs.begin(), vs.end());
27     vs.erase(new_end, vs.end());
28 }
29 
30 int main()
31 {
32     vector<string> v{ "1234", "1234", "1234", "Hi", "alan", "wang" };
33     elimdups(v);
34     stable_sort(v.begin(), v.end(), is_shorter);
35     cout << "ex10.11 :\n";
36     println(v);
37     system("pause");
38     return 0;
39 }

输出结果:

Exercise 10.14:

1 int main()
2 {
3     auto sum = [](int a, int b) {return a + b; };
4     cout << sum(1, 5) << endl;
5     return 0;
6 }

Exercise 10.16

猜你喜欢

转载自www.cnblogs.com/sunbines/p/10609861.html