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