C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

C++STLの配列アルゴリズム


C ++ 11以降、STLにはさまざまな関数が追加されています。これらの関数は、アルゴリズムヘッダーファイルにあります。ここでは、これのいくつかの機能を見ていきます。

  • all_of()関数は、コンテナのすべての要素に当てはまる1つの条件をチェックするために使用されます。アイデアを得るためのコードを見てみましょう

#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(all_of(arr, arr + n, [](int x){return x%2 == 0;})) {
      cout << "All are even";
   } else {
      cout << "All are not even";
   }
}

出力

All are even


  • any_of()関数は、1つの条件をチェックするために使用されます。これは、コンテナーの少なくとも1つの要素に当てはまります。アイデアを得るためのコードを見てみましょう。

#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10, 5, 62};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(any_of(arr, arr + n, [](int x){return x%2 == 1;})) {
      cout << "At least one element is odd";
   } else {
      cout << "No odd elements are found";
   }
}

出力

At least one element is odd


  • none_of()関数は、コンテナのどの要素も指定された条件を満たすかどうかをチェックするために使用されます。アイデアを得るためのコードを見てみましょう。

#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10, 5, 62};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(none_of(arr, arr + n, [](int x){return x < 0 == 1;})) {
      cout << "All elements are positive";
   } else {
      cout << "Some elements are negative";
   }
}

出力

All elements are positive


  • copy_n()関数は、ある配列の要素を別の配列にコピーするために使用されます。より良いアイデアを得るためにコードを見てみましょう。

#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10, 5, 62};
   int n = sizeof(arr)/sizeof(arr[0]);
   int arr2[n];
   copy_n(arr, n, arr2);
   for(int i = 0; i < n; i++) {
      cout << arr2[i] << " ";
   }
}

出力

2 4 6 8 10 5 62


  • itoa()関数は、連続値を配列に割り当てるために使用されます。この関数は、数値ヘッダーファイルの下にあります。 3つの引数が必要です。配列名、サイズ、および開始値。

#include <iostream>
#include <numeric>
using namespace std;
main() {
   int n = 10;
   int arr[n];
   iota(arr, arr+n, 10);
   for(int i = 0; i < n; i++) {
      cout << arr[i] << " ";
   }
}

出力

10 11 12 13 14 15 16 17 18 19

  1. 2D配列をC++関数に渡す

    配列は引数として関数に渡すことができます。このプログラムでは、2次元配列の要素を関数に渡して表示するように実行します。 アルゴリズム Begin The 2D array n[][] passed to the function show(). Call function show() function, the array n (n) is traversed using a nested for loop. End サンプルコード #include <iostream> using namespace std; void show(int n[4][3]); int

  2. 配列をC++関数に渡す

    C ++では、配列全体を引数として関数に渡すことはできません。ただし、インデックスなしで配列の名前を指定することにより、配列へのポインタを渡すことができます。 1次元配列を関数の引数として渡したい場合は、次の3つの方法のいずれかで関数の仮パラメーターを宣言する必要があります。3つの宣言メソッドはすべて、整数ポインターが実行されることをコンパイラーに通知するため、同様の結果を生成します。受け取る必要があります。 配列を関数に渡す方法は3つあります- ポインタとしての正式なパラメータ void myFunction(int *param) {    // Do so