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

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

Susan Sarandon
Susan Sarandon原创
2024-10-24 01:57:29497浏览

How to Use std::sort to Order an Array in C  ?

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

问题: 如何使用 C 标准模板库的 std::sort()按升序排列数组?

<code class="cpp">int v[2000];</code>

答案:在 C 11 中,您可以使用两个方便的函数:

<code class="cpp">std::sort(std::begin(v), std::end(v));</code>

附加问题: C 有办法确定数组的开始和结束位置吗?

答案: 是的,在 C 11 中,std::begin 和 std::end 是数组重载。

<code class="cpp">std::sort(std::begin(v), std::end(v));</code>

如果您使用的是早期版本的 C ,您可以创建自己的 begin 和 end 版本:

非常量:

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

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

常量:

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

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

C 样式数组的重载:

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

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

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

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