ตั้งแต่ C++11 มีฟังก์ชันต่างๆ ถูกเพิ่มเข้าไปใน STL ฟังก์ชันเหล่านี้อยู่ในไฟล์ header algorithm มาดูฟังก์ชันบางตัวกัน
ฟังก์ชัน all_of() ใช้ตรวจสอบเงื่อนไขหนึ่ง ว่าเป็นจริงสำหรับทุกองค์ประกอบของคอนเทนเนอร์ มาดูโค้ดเพื่อเข้าใจ
ตัวอย่าง
#include <iostream>
#include <algorithm>
using namespace std;
int 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;
int 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;
int 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; })) {
cout << "All elements are positive";
} else {
cout << "Some elements are negative";
}
}
ผลลัพธ์
All elements are positive
ฟังก์ชัน copy_n() ใช้คัดลอกองค์ประกอบของอาร์เรย์หนึ่งไปยังอีกอาร์เรย์หนึ่ง
ตัวอย่าง
#include <iostream>
#include <algorithm>
using namespace std;
int 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
ฟังก์ชัน iota() ใช้กำหนดค่าต่อเนื่องลงในอาร์เรย์ ฟังก์ชันนี้อยู่ใน header numeric รับ 3 อาร์กิวเมนต์: ชื่ออาร์เรย์, ขนาด, และค่าเริ่มต้น
ตัวอย่าง
#include <iostream>
#include <numeric>
using namespace std;
int 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