ホームページ  >  記事  >  バックエンド開発  >  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 では、2 つの便利な関数を利用できます:

<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 を作成できます:

Non-const:

<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>

Const:

<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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。