C++ Primer ex 7.14

A

arnuld

this programme work fine. any suggestions from you:


/* C++ Primer - 4/e
*
* exercise 7.13
* STATEMENT:
* write a programme to calculate the sum of the elements of
vector<double>
*
*/

#include <iostream>
#include <vector>

double sum_vector( std::vector<double> &dvec ) {
double sum = 0;
for( std::vector<double>::const_iterator iter=dvec.begin();
iter != dvec.end();
++iter )
{
sum += *iter;
}

return sum;
}


int main()
{
std::vector<double> dvec;

std::cout << "Enter some floating-point numbers: "; double d;

while( std::cin >> d )
{
dvec.push_back(d);
}


std::cout << "sum of all numbers = "
<< sum_vector( dvec )
<< std::endl;

return 0;
}
 
H

hurcan solter

you may use std::accumulate;


#include <iostream>
#include <vector>
#include <numeric>

int main()
{
std::vector<double> dvec;

std::cout << "Enter some floating-point numbers: "; double d;

while( std::cin >> d )
{
dvec.push_back(d);
}

std::cout << "sum of all numbers = "<<
std::accumulate(dvec.begin(),dvec.end(),0.0);

return 0;
}
 
F

Frank Birbacher

arnuld said:
this programme work fine. any suggestions from you:

Yes, use a typedef. I guess the next program is to do it with a list ;)
#include <iostream>
#include <vector>

typedef double Number;
typedef std::vector<Number> Sequence;

//take a reference to const
Number sumOfSequence(Sequence const& seq)
{
Number sum = 0;
for(Sequence::const_iterator ...


Frank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

C++ Primer ex 5.18 5
C++ Primer ex 3.14 8
Chatbot 0
C++ Primer exercise 3.13 17
C++ Primer ex 7.12 2
C++ Primer ex 4.30 10
C++ Primer ex 9.27 4
C++ Primer ex 7.20 - finding factorial 13

Members online

No members online now.

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,692
Latest member
JenniferTi

Latest Threads

Top