I am practicing with functions on the vector class. i have written a function ‘sumVector’ to add up all elements of vector ‘ages’, but it is not returning the total
i am copying my code block; i know the STL provides a sum function but this is for my own practice. i would appreciate if someone would point out what i am doing wrong
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
template<typename T>
int sumVector(const vector<T> &integers2)
{
typename vector<T>::const_iterator constIterator;
//display vector elements using constIterator
for
(constIterator=integers2.begin();
constIterator!=integers2.end();++constIterator);
int sum=0;
sum+=*constIterator;
return sum;
cout<<sum;
}
int main ()
{
vector<int> ages;
vector<float>var;
ifstream inFile;
inFile.open("data.txt");
if(!inFile)
{
cout<<"didn't work";
cin.get();
exit (1);
}
string line;
getline(inFile, line);
istringstream in(line);
copy(std::istream_iterator<int>(in),
std::istream_iterator<int>(),
std::back_inserter(ages));
cout<<ages.at(2)<<endl;
getline(inFile, line);
istringstream gin(line);
copy(istream_iterator<float>(gin),
istream_iterator<float>(),
back_inserter(var));
cout<<var.at(0)<<endl;
cout<<"whats the sum";
sumVector (ages);
cin.get();
inFile.close();
cin.get();
}
The
forloop is incorrect and thecout << sumoccurs after thereturnfromsumVector(). The return type (and type ofsum) should also beTotherwisesumVector()is restricted tovectors of elements ofint(or types convertible toints).Something like the following I think is what your looking for:
Consider not printing the value of
sumwithinsumVector()as (IMO) this is clearer:It may also be required to store the result of
sumVector()in a variable and not write anything to standard output at the point the sum is calculated.