调用标准::排序

Calling std::sort

本文关键字:排序 标准 调用      更新时间:2023-10-16

C++标准库中的sort称为:

sort (first element, last element);

所以如果我有一个数组:

int a[n];

我应该称sort为:

sort(&a[0], &a[n-1]);

因为a[0]是第一个元素,a[n-1]最后一个元素。但是,当我这样做时,它不会对最后一个元素进行排序。要获得完全排序的数组,我必须使用:

sort(&a[0], &a[n]);

这是为什么呢?

因为 stl 中的范围始终定义为从第一个元素迭代器到"一个过去结束"迭代器的半开放范围。使用 C++11,您可以使用:

int a[n];
sort(std::begin(a),std::end(a));

在 c++ 中 STL 中排序的格式是,

sort (first element, last element);

不,不是。正如您所发现的,您应该为第一个元素提供一个迭代器,以及一个过去结束的迭代器。

标准库通常使用半开放间隔来描述通过迭代器的范围。否则,将无法表示空范围:

// An empty container!
std::vector<int> v;
// Pretend that `v.end()` returns an iterator for the actual last element,
// with the same caveat as `v.begin()` that the case where no elements
// exist gives you some kind of "sentinel" iterator that does not represent
// any element at all and cannot be dereferenced
std::vector<int>::iterator a = v.begin(), b = v.end();
// Oh no, this would think that there's one element!
std::sort(a, b);