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
iota() फ़ंक्शन का उपयोग सरणी में सतत मान असाइन करने के लिए किया जाता है। यह फ़ंक्शन न्यूमेरिक हेडर फाइल के अंतर्गत मौजूद है। यह तीन आर्गुमेंट लेता है: सरणी नाम, आकार और प्रारंभिक मान।
उदाहरण
#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