std::get_temporary_buffer in C++

Hello everyone, in this tutorial, we will learn about the get_temporary_buffer in C++.

std::get_temporary_buffer

Generally, buffer refers to a block of computer memory that serves as temporary memory. So the get_temporary_buffer it allocates a block of temporary memory. It’s mostly used internally by the Standard Template Library(STL) in algorithms. It allocates an extra memory so the algorithm can be performed more efficiently.

Syntax

pair(int*, ptrdiff_t) a = get_temporary_buffer(int)(size)

Now, we will implement it in C++.
Code:

#include <iostream> 
#include <algorithm> 

using namespace std; 
void Sorting(int *arr, int n) 
{ 
    std::cout << " \nOriginal Array : ";
    for (int i = 0; i < n; i++) { 
        std::cout << arr[i] << " "; 
    }  
    pair<int*, ptrdiff_t> a = get_temporary_buffer<int>(n); //allocate a temporary block of memory of size n
  
    uninitialized_copy(arr, arr + a.second, a.first); //copied to buffer
    
    sort(a.first, a.first + a.second);   //function to sort
  
    std::cout << "\nSorted Array : "; 
    for (int i = 0; i < a.second; i++) { 
       std::cout << a.first[i] << " ";   //printing the sorted array
    }
    
} 


int main() 
{ 
    int n;
    std::cout<<"Enter the no of elements you want to sort : ";
    std::cin>>n;
    int arr[n];
    std::cout<<"Enter the elements you want to sort : ";
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
     
    Sorting(arr, n); 
    return 0; 
} 

 

OUTPUT:

Enter the no of elements you want to sort : 10 
Enter the elements you want to sort : 9 
1
5
3
2
7
8
4
6
0
Original Array : 9 1 5 3 2 7 8 4 6 0 
Sorted Array : 0 1 2 3 4 5 6 7 8 9

Explanation:

  1. First, take the input from the user of how many elements you want to sort and the elements you want to sort in the array.
  2. After taking the input call the function sort(arr,n)
  3. Now in function sort first print the unsorted array.
  4. Now a block of temporary memory is allocated using the get_temporary_buffer
    pair<int*, ptrdiff_t> a = get_temporary_buffer<int>(n);
  5. After allocating the memory copy the array elements in the temporary buffer using
    uninitialized_copy(arr, arr + a.second, a.first);
  6. Now, sort the array elements using the sort function.
    sort(a.first, a.first + a.second);
  7. Now, print the sorted array.

 

Also read,

Leave a Reply

Your email address will not be published. Required fields are marked *