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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP