简体   繁体   中英

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.

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)  );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM