ホームページ  >  記事  >  バックエンド開発  >  C で配列の並べ替えに std::sort を使用する方法

C で配列の並べ替えに std::sort を使用する方法

DDD
DDDオリジナル
2024-10-23 19:01:31496ブラウズ

How to Use std::sort for Array Sorting in C  ?

C での配列の並べ替えに std::sort を使用する方法

C 標準テンプレート ライブラリの std::sort 関数を使用した配列の並べ替え次のように実行できます:

<code class="cpp">int main() {
  int v[2000];
  std::sort(v, v + 2000);  // Sort the array
}</code>

ただし、C 0x/11 では std::begin 関数と std::end 関数が導入され、プロセスが簡素化されました:

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

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

If std:: begin と std::end は使用できません。次のように定義できます:

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

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

// Const version
template<class Cont>
typename Cont::const_iterator begin(Cont const& c) {
  return c.begin();
}

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

// Overloads for C-style arrays
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 を使用する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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