C++ stl最大元素算法产生的错误结果

C++ stl最大元素算法产生的错误结果,c++,gcc,stl,max,C++,Gcc,Stl,Max,我注意到std::max_元素在整数上有一种奇怪的行为,它们之间的差异不超过一个: #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";//i

我注意到std::max_元素在整数上有一种奇怪的行为,它们之间的差异不超过一个:

#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
}
#包括
#包括
#包括
int main()
{
向量v={1,2,3};

std::cout这实际上是正确的行为,只需注意
v.end()
基本上是一个超过最后一个元素,这意味着它不包括在内。对于
v.begin()+1
,情况也是如此-它不包括在内,它在
v.begin()之前停止
。查询最后两行中最大元素的范围仅包含一个元素。

这些范围超过了要传递的末端迭代器。