首页 > 后端开发 > C++ > 正文

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

Susan Sarandon
发布: 2024-10-24 01:57:29
原创
496 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!