简单std::排序不起作用

Simple std::sort not working

本文关键字:不起作用 排序 简单 std      更新时间:2023-10-16

我有以下代码:

int main()
{
    int intArr[] = { 1,5,3 };
    //auto f = [](auto a, auto b) {return a < b;};
    //std::sort(intArr, intArr + 2, f);
    std::sort(intArr, intArr + 2);
    for (int& temp : intArr)
        cout << temp << endl;
}

然而,输出是未排序的(例如,输出是1 5 3)。将std::sort与lambda一起使用时也会得到相同的结果。是什么导致了这种行为?

我使用的是Visual C++编译器(Visual Studio 2015)。

在采用范围的STL算法中,如果你想提供整个范围,你必须将一个元素的末尾作为结束,而不是范围本身的末尾,因此在你的情况下:

std::sort(intArr, intArr + 3);

std::sort(intArr, intArr + sizeof(intArr) / sizeof(int));

甚至更好:

std::sort(std::begin(intArr), std::end(intArr));

数组中有3个值,但只发送2个(因为在STL算法中,第二个参数是past-end iterator)。应该是

std::sort(intArr, intArr + 3);