Possible duplicate:sum of elements instd::vector
std::vector
I want to sum the std :: vector elements
for instance
std::vector<int > MYvec; /*some push backs*/ int x=sum(MYVec); //it should give sum of all the items in the vector
How to write a function sum?
sum
I tried this
int sum(const std::vector<int> &Vec) { int result=0; for (int i=0;i<Vec.size();++i) result+=Vec[i]; return result; }
However i don't like my approach
Try using accumulate from the C ++ standard library. Something like that:
#include <vector> #include <numeric> // Somewhere in code... std::vector<int> MYvec; /*some push backs*/ int sum = std::accumulate( MYvec.begin(), MYvec.end(), 0 );
You must use std::accumulate.
std::accumulate
int main() { std::vector<int> vec; // Fill your vector the way you like int sum = std::accumulate(vect.begin(), vect.end(), 0); // 0 is the base value std::cout << sum << std::endl; return 0; }
Isent std:: accumulate, ?
, . ,
int sum = 0; for(unsigned i = 0; i < Myvec.size(); i++){ sum += MYvec[i]; }
Source: https://habr.com/ru/post/1758511/More articles:Extract all words starting with a specific letter from wordnet - cHow to save a session as windows? - c #The most memory efficient way to store base64 data in Python? - pythonWhat is the difference between a string and a string? - c #Настройка шириныдля размещения элементов меню с помощью jQuery - jqueryWhy can't I compile this program other than CLR in VC ++ 2008? How to do it? - c ++Установка шириныдля размещения элементов меню - javascriptGet current URL with Chrome extension - javascriptWhy I got "Access Denied". (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) "when creating a user in Active Directory - c #Authentication of WPF and WCF data services at the request level? - wpfAll Articles