Reputation: 43
I'm trying to learn to use iterator with vectors in C++ by, for example computing the average of a vector.
Yet this code does not give the proper answer and I cannot figure out why !
double average(vector<double> const &v)
{
vector<double>::size_type taille = v.size();
double sum = 0;
for(vector<double>::const_iterator i = v.begin(); i != v.end(); ++i)
sum += v[*i];
return sum/taille;
}
Can anybody give me a hint ?
Thanks a lot in advance ! Bye :)
Upvotes: 0
Views: 5933
Reputation: 1029
The iterator actually points to the object. Proper way to iterate is:
double average(vector<double> const &v)
{
vector<double>::size_type taille = v.size();
double sum = 0;
for(vector<double>::const_iterator i = v.begin(); i != v.end(); ++i)
sum += *it;
return sum/taille;
}
In C++11 you can do this too:
double average(vector<double> const &v)
{
double sum = 0;
for(const double &d : v)
sum += d;
return sum/v.size();
}
Upvotes: 1
Reputation: 361532
In C++, iterators imitate the behaviors of pointers (to some degree). So if it
is an iterator to an element, you access the element by dereferencing it as *it
.
That means, instead of this:
sum += v[*i];
you should write this:
sum += *i; //just dereference the iterator!
Hope that helps.
Upvotes: 4
Reputation: 11058
Accessing vector items through an iterator is simply *i
, not v[*i]
. The form you've used requires accessing with index:
for (size_t i = 0; i < v.size(); i++) sum += v[i];
And your code should look like:
for(vector<double>::const_iterator i = v.begin(); i != v.end(); ++i)
sum += *i;
^^^^ note this
Upvotes: 1