rohitt
rohitt

Reputation: 127

iterators for std::accumulate

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

Answers (1)

john
john

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

Related Questions