DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

std::deque c++

Definition

This container comes under sequential container. It is template class to store element of any type (in build as well as user defined data type) in sequentially order. It provides the same interface as vector and BUT it has extra feature it can do fast insertion and deletion at beginning as well as end of container (vector does not do fast insertion and deletion at beginning). In other word it has both property of vector and list.

Header File

#include<deque>

Key Points

  • Good performance for insertion and deletion at both beginning and end.
  • It does not store element in continuous memory.
  • It can grow both side (unlike vector grow only in one direction).

Disadvantage

  • Performance while Insertion or deletion at middle is NOT good.

Source code of std::deque with example

/*
Program: STL Deque
Author: Alpha Master
Date: 15 September 2021
*/

//Header File
#include<iostream>
#include<deque>

//Display function the show the content of list
void display(std::deque<int>& lst)
{
    //using iterate to transverse the list and display the content
    std::deque<int>::iterator itr;
    for(itr = lst.begin(); itr != lst.end(); itr++)
    {
        std::cout<<*itr<<" ";
    }
    std::cout<<std::endl;
}
int main()
{
    std::cout<<"STL Deque"<<std::endl;

   //Create empty deque object
    std::deque<int> lst;
    std::cout<<"size:"<<lst.size()<<std::endl;
 
    //Add element in vector at end 
    lst.push_back(1);
    lst.push_back(2);
    lst.push_back(3);
    lst.push_back(4);
    lst.push_back(5);
    std::cout<<"size:"<<lst.size()<<std::endl;
    
    //display content
    display(lst);

    //Add element at begining
    lst.push_front(11);
    lst.push_front(12);
    
    //display
    display(lst);

    //Access using index
    std::cout<<"Random access, get 3 position element:"<<lst[2]<<std::endl;
    std::cout<<"Random access, get 6 position element:"<<lst[5]<<std::endl;

    return 0;
}

Output

STL Deque
size:0
size:5
1 2 3 4 5 
12 11 1 2 3 4 5 
Random access, get 3 position element:1
Random access, get 6 position element:4

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer