关于STL中函数对象的问题
1个回答
展开全部
算法和函数对象,算法和容器类(通过容器类的迭代器),函数对象和类对象都是通过参数联系起来的,属于松散耦合的。下面是个典型的例子:
#include <iostream>
#include <vector>
#include <numeric>
#include <functional>
using namespace std;
template <class T>
class SumSquares : binary_function<T, T, T> {
public:
const T operator()(const T& total, const T& value) {
return total + value * value;
}
};
int main() {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
int result = accumulate(v.begin(), v.end(), 0, SumSquares<int>());
cout << result << endl;
return 0;
}
#include <iostream>
#include <vector>
#include <numeric>
#include <functional>
using namespace std;
template <class T>
class SumSquares : binary_function<T, T, T> {
public:
const T operator()(const T& total, const T& value) {
return total + value * value;
}
};
int main() {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
int result = accumulate(v.begin(), v.end(), 0, SumSquares<int>());
cout << result << endl;
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询