调用标准::排序
Calling std::sort
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);
相关文章:
- 在C++标准中,语法选项的表示中没有隐含的排序,这种说法正确吗
- 标准::map键类型的严格弱排序概念
- 如果要求比较器是严格的总排序,而不仅仅是严格的弱排序,C++标准算法会更快吗?
- 解释标准库排序函数C++的比较谓词的工作原理?
- 如何将标准::矢量插入具有自定义排序功能的 std::set 中
- 如何按降序对标准数组进行排序 - C++ 11.
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- 有没有办法为集合指定不同的唯一性和排序标准
- 使用标准库根据一个数组对两个数组进行排序(避免复制步骤)
- 是否存在用于按以下方式对两个范围进行排序和分区的标准算法?
- 根据标准对结构向量进行排序,然后显示结果
- 使用标准库对矢量的矢量进行排序,并计算唯一出现的频率
- 如何在c++中使用两个排序标准(对于一组对)创建有序集
- 是否按多个标准进行快速排序
- 对标准库容器类型进行排序的static_assert() 的优雅方式
- 对变量上的标准构造进行排序
- 排序标准::映射<字符串,双精度>
- 排序这些单词的排序标准
- 具有多个排序标准的对象的排序向量
- C++ 标准::排序 标准::矢量<Object> - 错误太多