Reputation: 127
The error seems to be with std:: accumulate()
or the iterators, or am I accessing an invalid pointer?
int m = 0;
std::vector<int> v{4,-3,0,-5};
for(std::vector<int>::iterator i = v.begin(); i != v.end(); i++)
{
for(std::vector<int>::iterator j = v.begin(); j != v.end(); j++)
{
m = max( m, std::accumulate(i, j, 0) );
}
}
I've tried the above code, but the program stops unexpectedly.
Upvotes: 1
Views: 288
Reputation: 87959
The problem is that j
can be less than i
. This version works
int m = 0;
std::vector<int> v{4,-3,0,-5};
for(std::vector<int>::iterator i = v.begin(); i!=v.end(); i++)
{
for(std::vector<int>::iterator j = i; j!=v.end(); j++)
// ^^^^^^
{
m = max( m, std::accumulate(i, j, 0) );
}
}
Upvotes: 4