调用std :: sort

时间:2015-01-23 16:17:13

标签: c++ sorting std

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

为什么会这样?

2 个答案:

答案 0 :(得分:6)

因为stl中的范围总是定义为从第一个元素迭代器到“一个接一个”结束的半开放范围。使用C ++ 11,您可以使用:

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

答案 1 :(得分:2)

  

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

sort (first element, last element);

不,不是。您应该为第一个元素提供一个迭代器,并且如您所发现的那样为一个过去的迭代器提供。

标准库通常使用semi-open intervals来描述通过迭代器的范围。否则就不可能表达空范围:

// 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);
相关问题