C++ vector::get_allocator() Function



The C++ vector::get_allocator() function is used to allocated chunks of Memory. It returns a copy of allocator object related to the container. It is defined in vector, map, list, and set library. The time complexity of the get_allocator() function is constant.

In STL, containers can change their size dynamically. Allocator is an object that is responsible to dynamic memory allocation/deallocation. All C++ Standard Library containers, with the exception of std::array, have a template parameter of type allocator<Type>, where Type denotes the type of the container element.

Syntax

Following is the syntax for C++ vector::get_allocator() Function −

allocator_type get_allocator() const noexcept;

Parameters

It doesn't accept any kind of parameters.

Example 1

Let's consider the following example, where we are going to use get_allocator() function.

#include <iostream>
#include <vector>
using namespace std;

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};
   int *p = NULL;
   p = v.get_allocator().allocate(5);
   for (int i = 0; i < 5; ++i)
      p[i] = i + 1;
   for (int i = 0; i < 5; ++i)
      cout << p[i] << endl;
   return 0;
}

Output

When we compile and run the above program, this will produce the following result −

1
2
3
4
5

Example 2

Considering the another scenario, where we are going to returns a copy of same allocator object used by the vector tutorial.

#include <iostream>
#include <vector>
using namespace std;

int main (){
   vector<int> tutorial;
   int *x;
   x = tutorial.get_allocator().allocate(6);
   for(int i=0; i<6; i++)
      tutorial.get_allocator().construct(&x[i], 2*(i+1));
   cout<<"The allocated array elements: ";
   for(int i=0; i<6; i++)
      cout<<x[i]<<" ";
   for(int i=0; i<6; i++)
      tutorial.get_allocator().destroy(&x[i]); 
      tutorial.get_allocator().deallocate(x,6);
   return 0;
}

Output

On running the above program, it will produce the following result −

The allocated array elements: 2 4 6 8 10 12 
Advertisements