我注意到 std::max_element 在整数上有一个奇怪的行为,它们相差不超过一个:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> v = {1, 2, 3};
std::cout<<*std::max_element(v.begin(), v.end())<<"\n";//it's ok - correct answer
std::cout<<*std::max_element(v.begin(), v.begin()+1)<<"\n";//compare between 1 and 2: answer - 1
std::cout<<*std::max_element(v.begin()+1, v.begin()+2)<<"\n";//compare between 2 and 3: answer - 2
}
我在 64 位 linux 上使用 gcc 4.8 编译器。 这是编译器的错误,还是其他原因?
最佳答案
这实际上是正确的行为,请注意 v.end()
基本上是最后一个元素之后,这意味着它不包括在内。 v.begin()+1
也是如此 - 它不包括在内,它就在 v.begin()
之前停止。您在最后两行中查询最大元素的范围仅包含一个元素。
关于c++ - STL max_element 算法产生的错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19471272/