qfedu-cpp-level/day10/stl_algorithm_demo/f1.cpp

60 lines
1.3 KiB
C++
Raw Permalink Normal View History

2023-08-14 17:20:39 +08:00
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
// template <typename T>
void print(typename set<int>::const_iterator start,
typename set<int>::const_iterator end, plus<int> pl, int m)
{
for (; start != end; start++)
{
cout << pl(*start, m) << " ";
}
cout << endl;
}
void print(typename set<int>::const_iterator start,
typename set<int>::const_iterator end, multiplies<int> mul, int m)
{
for (; start != end; start++)
{
cout << mul(*start, m) << " ";
}
cout << endl;
}
void show(int n)
{
cout << n << " ";
}
// 二元仿函数
class PrintPlus : public binary_function<int, int, void>
{
public:
void operator()(const int &n1, const int &n2) const
{
cout << n1 << "+" << n2 << " = " << n1 + n2 << endl;
}
};
int main()
{
int m[] = {1, 2, 3, 4, 8, 5, 1, 2};
// set 会自动过滤重复,并排序
set<int> s(m, m + sizeof(m) / sizeof(m[0]));
// print(s.begin(), s.end(), plus<int>(), 1);
// print(s.begin(), s.end(), multiplies<int>(), 3);
// for_each(s.begin(), s.end(), show);
// cout << endl;
// PrintPlus 测试
// for (int i = 0; i < 6; i++)
for_each(s.begin(), s.end(), bind1st(PrintPlus(), i));
return 0;
}