STL은 다음 여섯 가지 산술 연산 함수 객체(함수자)를 제공한다
plus<T>: 이항 연산 함수자로 + 연산
minus<T>: 이항 연산 함수자로 - 연산
multiplies<T>: 이항 연산 함수자로 * 연산
divides<T>: 이항 연산 함수자로 / 연산
modulus<T>: 이항 연산 함수자로 % 연산
negate<T>: 이항 연산 함수자로 - 연산
//STL plus 사용
int main(){
plus<int> oPlus;
//1. oPlus 객체로 더하기 암묵적 호출
cout<<oPlus(10, 20)<<endl;
//2. oPlus 객체로 더하기 명시적 호출
cout<<oPlus.operator()(10,20)<<endl;
//3. 임시 객체로 더하기 암묵적 호출 (일반적으로 사용)
cout<<plus<int>()(10,20)<<endl;
//4. 임시 객체로 더하기 명시적 호출
cout<<plus<int>().operator()(10,20)<<endl;
return 0;
}
//사용자 Plus
template<typename T>
struct Plus: public binary_function<T,T,T>
{
T operator()(const T& left, const T& right) const{
return left+right;
}
};
int main(){
Plus<int> oPlus;
cout<<oPlus(10, 20)<<endl;
cout<<oPlus.operator()(10,20)<<endl;
cout<<Plus<int>()(10,20)<<endl;
cout<<Plus<int>().operator()(10,20)<<endl;
return 0;
}
//산술 연사 함수자와 알고리즘
int main(){
vector<int> v1; // 10,20,30,40,50
vector<int> v2; // 1, 2, 3, 4, 5
vector<int> v3(5);
//v3=v1+v2
transform(v1.begin(),v1.end(),v2.begin(),v3.begin(),plus<int>());
//v3=v1*v2
transform(v1.begin(),v1.end(),v2.begin(),v3.begin(),multiplies<int>());
//v3 = -v1
transform(v1.begin(),v1.end(),v2.begin(),v3.begin(),negate<int>());
//v3 = v1.right - v1.left
adjacent_difference(v1.begin(),v1.end(),v3.begin(),minus<int>());
//v3 = v1* sum;
// sum=v3
partial_sum(v1.begin(),v1.end(),v3.begin(),multiplies<int>());
//v1 모든 원소의 곱
accumulate(v1.begin(), v1.end(),1,multiplies<int>());
return 0;
}