Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++ 벡터의 요소를 요약하는 방법은 무엇입니까?

<시간/>

C++ 벡터의 모든 요소를 ​​합산하는 것은 std::accumulate 메소드를 사용하여 매우 쉽게 수행할 수 있습니다. 헤더에 정의되어 있습니다. 벡터에 지정된 모든 값을 지정된 합계로 누적합니다.

알고리즘

Begin
   Declare v of vector type.
      Initialize some values into v vector in array pattern.
      Print “Sum of all the elements are:”.
      Call accumulate(v.begin(),v.end(),0) to calculate the sum of all
      values of v vector.
      Print the result of sum.
End.

예시 코드

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
   vector<int> v = {2,7,6,10};
   cout<<"Sum of all the elements are:"<<endl;
   cout<<accumulate(v.begin(),v.end(),0);
}

출력

Sum of all the elements are:
25