首页  >  文章  >  后端开发  >  如何:在 C 中使用 std::sort 对数组进行排序

如何:在 C 中使用 std::sort 对数组进行排序

Barbara Streisand
Barbara Streisand原创
2024-10-23 21:00:02845浏览

How to: Sort an Array Using std::sort in C

在 C 语言中使用 std::sort 对数组进行排序

在 C 语言中,标准模板库提供了 std::sort() 函数来高效地对数组中的元素进行排序。对于声明为 int v[2000] 的数组,以下代码片段演示了如何使用 std::sort() 来实现此目的:

<code class="cpp">#include <algorithm>

int main() {
  int v[2000];
  std::sort(std::begin(v), std::end(v));
}</code>

但是,std::begin() 和 std: C 0x/11 中引入的 :end() 函数对于这种方法至关重要。这些函数返回代表给定容器(包括数组)开始和结束的迭代器。

如果您无权访问 C 0x,可以自己定义这些函数:

非常量容器的开始函数:

<code class="cpp">template<class Cont>
typename Cont::iterator begin(Cont& c) {
  return c.begin();
}</code>

非常量容器的结束函数:

<code class="cpp">template<class Cont>
typename Cont::iterator end(Cont& c) {
  return c.end();
}</code>

开始函数const 容器:

<code class="cpp">template<class Cont>
typename Cont::const_iterator begin(Cont const& c) {
  return c.begin();
}</code>

const 容器的结束函数:

<code class="cpp">template<class Cont>
typename Cont::const_iterator end(Cont const& c) {
  return c.end();
}</code>

C 样式数组的重载:

<code class="cpp">template<class T, std::size_t N>
T* begin(T (&arr)[N]) {
  return &arr[0];
}

template<class T, std::size_t N>
T* end(T (&arr)[N]) {
  return arr + N;
}</code>

通过使用这些函数,您可以在 C 中使用 std::sort() 对数组进行无缝排序。

以上是如何:在 C 中使用 std::sort 对数组进行排序的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn