행렬의 덧셈을 구하는 문제를 풀다가 이전에 배열의 내적계산을 쉽게 할 수 있는 <numeric> 헤더에 포함 되어 있는std::inner_product 를 배웠던 기억이 있어서, 길이가 같은 배열의 덧셈을 쉽게 할 수 있는 라이브러리가 있나 하고 찾아봤는데, 직접적인 구현은 없었다.
*내적 계산: https://dong-grae.tistory.com/45
std::inner_product(내적 계산)
#include #include using namespace std;int solution(vector a, vector b) { int answer = 0; for(int i = 0; i 처음에는 반복문을 통해 직접 배열의 시작과 끝을 순회하며 a[i] * b[i] 의 값을 answer 변수에 더 해가며 저장했는데,
dong-grae.tistory.com
비슷하게 구현할 수 있는 것은 <algorithm> 헤더에 정의되어 있는 std::transform을 활용하는 것이다.
std::transform
// 단일 입력 범위
template<class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt first, InputIt last, OutputIt d_first, UnaryOperation unary_op);
// 두 개의 입력 범위
template<class InputIt1, class InputIt2, class OutputIt, class BinaryOperation>
OutputIt transform(InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt d_first, BinaryOperation binary_op);
입력 범위의 각 요소들에 연산자 혹은 적용 함수를 적용해서 그 결과를 출력 범위에 저장하는 기능을 한다.
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> Array1 = { 2,4,6,8,10 };
vector<int> Array2 = { 1,3,5,7,9 };
vector<int> Result(Array1.size());
transform(Array1.begin(), Array1.end(), Array2.begin(), Result.begin(), plus<int>());
return 0;
}
결과를 담을 배열은 최소 입력 범위의 크기만큼의 공간은 있어야한다.
'내배캠 > C++' 카테고리의 다른 글
std::fixed / std::setprecision (0) | 2024.12.26 |
---|---|
std::cin::fail / std::cin::clear / std::cin::ignore (0) | 2024.12.26 |
템플릿 함수 (0) | 2024.12.24 |
스마트 포인터 (0) | 2024.12.24 |
Stack / Static / Heap (2) | 2024.12.24 |