-3

I have a little question. How do I do to sum up all the numbers in a list packs? For example: List 1 is :

0.03326
0.02712
0.02178
0.01918
0.01751
0.01671
0.01602
0.0156
0.01549
0.01543
0.01568
0.01625
0.01658
0.01732
0.0178
0.01827
0.01855
0.01895
0.01949
0.02017
0.0211
0.02213
0.0236
0.02753
0.04504
0.09489
0.10131
0.11255

I want to sum up all the numbers.

SheetJS
  • 22,470
  • 12
  • 65
  • 75
chofor marius
  • 1
  • 1
  • 1
  • 1

3 Answers3

6

Use std::accumulate. It will return the arithmetic sum of all the elements in the list.

double sum = std::accumulate(std::begin(list), std::end(list), 0.0);
digital_revenant
  • 3,274
  • 1
  • 15
  • 24
  • Thanks a lot for the propositions. I found an easier method by try and error. double result = sum(myList()); Info <<"sum is: "<< result<< endl; – chofor marius Oct 30 '13 at 14:25
  • @choformarius With this method you don't have to define your own `sum` function. – digital_revenant Oct 30 '13 at 14:27
  • I wouldn't consider writing the function myself easier than using the function provided by the Standard Library specifically for this purpose. Also, do yourself a favour, and stop using [`using namespace std;`](http://stackoverflow.com/q/1452721/1171191) and [`std::endl`](http://kuhllib.com/2012/01/14/stop-excessive-use-of-stdendl/). – BoBTFish Oct 30 '13 at 14:29
1

Do the same like following:

double sum=0;
for (std::list<double>::iterator it=mylist.begin(); it != mylist.end(); ++it){
    sum+=*it;
}

Hope it may help you :)

0

Assuming you're using std::list,

double total = 0;
for (std::list<double>::const_iterator iterator = list1.begin(), end = list1.end(); iterator != end; ++iterator) {
    total += *iterator;
}
return total;
Kvothe
  • 467
  • 4
  • 13