เนื่องจาก 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