top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How am I suppose to find sum of std::vector of integers?

+1 vote
53 views
How am I suppose to find sum of std::vector of integers?
posted Aug 4, 2016 by Shahsikant Dwivedi

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+3 votes
 
Best answer

Iterate till end and take the sum

for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
    sum += *it;

Or you can use std::accumulate(vector.begin(), vector.end(), 0); if needs a library function.

answer Aug 4, 2016 by Salil Agrawal
Thanks, sir but I am wondering whether there is any standard way to find the sum, as we sort the vector elements by using sort()  function.
You may have missed the second part there is something called accumulate but part of library numeric.
My apologies for missing the second part , but I have one more question about the third argument, is it the initial value that accumulate will return and what if it is 0.0?
I think its the init value so if you set the init value to be 5 then sum will be sum +5.
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...