//accumulate 함수의 원문
#include <numeric>
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init);
template <class InputIterator, class T, class BinaryOperation>
T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);
accumulate(구간의 시작 값, 구간의 마지막 값 , 초기 값)
-지정한 구간에 속한 값들을 모든 더한 값을 계산한다.
-기본적으로 더하기 연산, 조건자 이용시 이외의 연산 가능 (binary_op)
-필요 헤더 : <numeric>
예제 코드)
#include <iostream>
#include <vector>
#include <numeric>
void main()
{
std::vector<int> v1 = { 1,2,3,4 };
int result = std::accumulate(v1.begin(), v1.end(), 0);
std::cout << result;
return;
}
//출력결과
//10
//1 + 2 + 3 + 4 = 10
//inner_product 함수 원문
#include <numeric>
template <class _InIt1, class _InIt2, class _Ty, class _BinOp1, class _BinOp2>
_Ty inner_product(_InIt1 _First1, _InIt1 _Last1, _InIt2 _First2, _Ty _Val, _BinOp1 _Reduce_op, _BinOp2 _Transform_op)
template <class _InIt1, class _InIt2, class _Ty>
_Ty inner_product(const _InIt1 _First1, const _InIt1 _Last1, const _InIt2 _First2, _Ty _Val)
inner_product는 내적이란 뜻이며 벡터(방향,크기를 가지고있는 값)를 마치 수처럼 곱하는 개념)을 뜻한다.
a라는 std::vecotr<int> b라는 std::vecotr<int> 있다고 가장할때
inner_product(시작값a,마지막값a,시작값b,초기값);
-두 입력값의 내적을 계산하는 알고리즘으로 기본적으로 +,*을 사용한다.
-반환값은 a,b의 값을 곱한뒤 서로 더한값이다.
-두번째(b)의 크기는 첫번째(a)의 크기보다 크거나 같아야한다.
p.s 벡터의 내적은 벡터의 곱(dot product) 라고도 부르며 벡터 사이의 크기(스칼라)를 나타날때 사용된다.
(수학 - 벡터 관련 수학 작성후 링크 필요)
예제코드)
#include <iostream>
#include <vector>
#include <numeric>
void main()
{
std::vector<int> v1 = { 1,2,3 };
std::vector<int> v2 = { 4,5,6 };
int result = std::inner_product(v1.begin(),v1.end(),v2.begin(),0);
std::cout << result;
return;
}
//출력결과
//32
//0(초기값) + (1 * 4) + (2 * 5) + (3 * 6) = 32
'C++' 카테고리의 다른 글
unique() (vector의 중복 값 제거) (0) | 2023.06.12 |
---|---|
std::vector (reverse_iterator,rbegin(),rend(),역방향반복자,내림차순정렬) (0) | 2023.06.09 |
문자집합(Character Set) (0) | 2023.06.04 |