STL应用
代码:
#include <iostream>
#include <vector>
using namespace std;
// 取反
template<typename T>
class negatation {
public:
T operator()(T input)
{
return -input;
}
};
// 平方
template<typename T>
class square {
public:
T operator()(T input)
{
return pow(input, 2);
}
};
// 立方
template<typename T>
class cubic {
public:
T operator()(T input)
{
return pow(input, 3);
}
};
// 遍历序列并进行相应的操作
template<typename input, class function>
void traverse(input first, input last, ostream& os, function op)
{
for (; first != last; ++first)
os << op(*first) << " ";
}
int main() {
const int N = 5;
vector<int> s(N);
for (int i = 0; i < N; i++)
cin >> s[i];
cout << "取反:";
traverse(s.begin(), s.end(), cout, negatation<int>());
cout << endl;
cout << "平方:";
traverse(s.begin(), s.end(), cout, square<int>());
cout << endl;
cout << "立方:";
traverse(s.begin(), s.end(), cout, cubic<int>());
cout << endl;
return 0;
}
结果: