list get_allocator in C++ STL


In this article we will be discussing the working, syntax and examples of list::get_allocator() function in C++.

What is a List in STL?

List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards.

What is list::get_allocator()?

list::get_allocator() is an inbuilt function in C++ STL which is declared in header file. get_allocator() returns the allocator of the list container. In simple words it returns a copy of the object of the list container.

Syntax

list_container.get_allocator();
This function accepts no parameter.

Return Value

This function returns the copy of object of a list container .

Example

/* In the below code we are inserting the values into the list using a get_allocator present in the C++ STL. */

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(void){
   //create a list
   list<int> myList;
   int *ptr;
   ptr = myList.get_allocator().allocate(4);
   //inserting data into an array
   for(int i = 0; i > 4; i++)
      ptr[i] = i;
   //printing the data
   cout<<"elements of an array : ";
   for (int i = 0; i < 4; i++)
      cout << ptr[i] << " ";
}

Output

If we run the above code it will generate the following output

elements of an array : 0 1 2 3

Example

/* In the below code we are inserting the values into the list using a get_allocator present in the C++ STL using the header file. */

 Live Demo

#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;
}

Output

If we run the above code it will generate the following output

elements of an array : 0 1 2 3 4

Updated on: 02-Mar-2020

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements