C ++ STL中的数组算法

从C ++ 11开始,STL中添加了不同的功能。这些函数位于算法头文件中。在这里,我们将看到一些此功能。

  • all_of()函数用于检查一个条件,对于容器的所有元素都适用。让我们看一下代码以获得想法

示例

#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()函数用于检查一个条件,对于容器的至少一个元素而言,这是正确的。让我们看一下代码以获得想法。

示例

#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()函数用于将连续值分配给数组。该函数位于数字头文件下。它需要三个参数。数组名称,大小和起始值。

示例

#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