C++ 문제 풀이/프로그래머스

[프로그래머스/C++] 내적

leejy811 2024. 1. 14. 17:40

1. 문제 설명

2. Solution

#include <string>
#include <vector>

using namespace std;

int solution(vector<int> a, vector<int> b) {
    int answer = 0;
    
    for(int i = 0;i < a.size();i++) {
        answer += a[i] * b[i];
    }
    return answer;
}

 

이 문제는 그냥 벡터의 모든 요소들을 내적하면 되는 아주 간단한 문제이고 곱해서 더해주어 간단하게 해결하였다. 하지만 뭔가 내적을 해주는 라이브러리가 있을 것 같았고 다른 사람의 풀이를 보다가 찾았다.

#include <vector>
#include <numeric>
using namespace std;

int solution(vector<int> a, vector<int> b) {    
    return inner_product(a.begin(),a.end(),b.begin(),0);
}

 

바로바로 <numeric> 헤더파일이다. 앞으로 수학 관련 라이브러리가 없는 것 같다면 numeric을 찾아보자

 

https://github.com/leejy811/AlgorithmStudy/tree/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/Lv.1/70128.%E2%80%85%EB%82%B4%EC%A0%81