इस लेख में हम C++ में list::get_allocator() फंक्शन के कार्य, सिंटैक्स और उदाहरणों पर चर्चा करेंगे।
list::get_allocator() क्या है?
list::get_allocator() C++ STL में एक इनबिल्ट फंक्शन है जो हेडर फाइल में घोषित है। get_allocator() लिस्ट कंटेनर का एलोकेटर (allocator) लौटाता है। सरल शब्दों में, यह लिस्ट कंटेनर के ऑब्जेक्ट की एक प्रति लौटाता है।
सिंटैक्स
list_container.get_allocator();
यह फंक्शन कोई पैरामीटर स्वीकार नहीं करता।
रिटर्न मान
यह फंक्शन लिस्ट कंटेनर के ऑब्जेक्ट की एक प्रति लौटाता है।
उदाहरण 1: एलोकेटर से मेमोरी आवंटित करना
#include <bits/stdc++.h>
using namespace std;
int main(void) {
list<int> myList;
int* ptr;
ptr = myList.get_allocator().allocate(4);
for (int i = 0; i < 4; i++)
ptr[i] = i;
cout << "elements of an array: ";
for (int i = 0; i < 4; i++)
cout << ptr[i] << " ";
myList.get_allocator().deallocate(ptr, 4);
return 0;
}
आउटपुट
elements of an array: 0 1 2 3
उदाहरण 2: हेडर फाइल के साथ
#include <iostream>
#include <list>
int main() {
std::list<int> myList;
int* ptr;
ptr = myList.get_allocator().allocate(5);
for (int i = 0; i < 5; ++i)
ptr[i] = i;
std::cout << "elements of an array: ";
for (int i = 0; i < 5; ++i)
std::cout << ' ' << ptr[i];
myList.get_allocator().deallocate(ptr, 5);
return 0;
}
आउटपुट
elements of an array: 0 1 2 3 4
व्याख्या
get_allocator()लिस्ट द्वारा उपयोग किए जाने वाले एलोकेटर ऑब्जेक्ट की कॉपी लौटाता है।- एलोकेटर के
allocate(n)से n तत्वों के लिए रॉ मेमोरी मिलती है। deallocate(ptr, n)से मेमोरी मुक्त करना न भूलें।- आमतौर पर कस्टम एलोकेटर्स लिखते समय उपयोगी होता है।