You are on page 1of 40

| C++ Containers

C++ STL CONTAINERS

STL CONTAINERS
• STL stands for Standard Template Library
• Container is an object which is used to store a set of objects with a
particular type
TYPES OF CONTAINERS
• C++ supports three types of containers. They are
1. Sequential Containers
2. Associative Containers
3. Unordered Associative Containers

Container Types

Sequential Associative Unordered


Containers Containers Containers

Examples

Containers in C++ Page 1


| C++ Containers

1. SEQUENTIAL CONTAINERS
• Here elements are arranged in sequential order
• This can be implemented either using array or linked list.
Examples
• Array
• Vector
• Forward List (Singly Linked List)
• List (Doubly Linked List)
• Deque
Vector
• Vector is a dynamic array in c++ and available in the header file
<vector>
• Like array, it is used to store the elements of a specified type.
Required Header File
#include<vector>
Syntax
vector<type> name;

Where,

• Type can be any base types like int, char*, float, char, bool, etc,
Example

vector<int> lb;

Containers in C++ Page 2


| C++ Containers

DIFFERENCE BETWEEN ARRAY AND VECTOR


S.N ARRAY VECTOR
1. It is static array and might It is dynamic memory and might
allocated on stack memory allocated on heap memory
2. Here elements can be retrieved Here elements can be retrieved
using indexing using indexing or iterator or at()
method
3. No need to import the header Header file <vector> should be
file <vector> imported
4. Example: Example:
int arr[50] vector<int> db;

IMPORTANT METHODS OF VECTOR CLASS


1. push_back(ele)
• It is an instance method of vector class
• It is used to add the elements of specified type to end of the vector
• It takes only one argument which is a particular type like int / float /
char etc,.
• Return type: void
2. pop_back()
• It is an instance method of vector class
• It is used to remove the top element (last element) from the vector
• It does not take any arguments
• Return type: void
3. size()
• It is an instance method of vector class
• It is used to display or return the total number of elements in the vector
• Return type: size_type
Containers in C++ Page 3
| C++ Containers

4. empty()
• It is an instance method of vector class
• This method is used to check whether vector is empty or not
• It does not take any arguments
• Return type: bool
5. clear()
• It is an instance method of vector class
• It is used to remove all the elements in the vector
• It does not take any arguments
• Return type: void
I. EXAMPLE OF INTEGER VECTOR
SOURCE CODE
// add iostream for basic c++ support and IO operations
#include<iostream>
// add vector header file
#include<vector>
using namespace std;
int main()
{
cout<<"--------------------------------------\n";
cout<<"\t Intger Vector Example\n";
cout<<"--------------------------------------\n";
// create an empty vector of int type
vector<int> vd;
// add elements to end of the vector
vd.push_back(12);
vd.push_back(18);
vd.push_back(24);
vd.push_back(41);

Containers in C++ Page 4


| C++ Containers

vd.push_back(50);
// display the elements in vector
for(int i=0;i<vd.size();i++)
{
cout<<" "<<vd[i]<<"\n";
}
return 0;
}

OUTPUT

Containers in C++ Page 5


| C++ Containers

II. EXAMPLE OF DYNAMIC VECTOR


(add, remove, display)
SOURCE CODE
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
class DynamicArray
{
public:
// define integer vector
vector<int> db;
int i,n,ele;
char user[30];
// push (add) the elements to end of the vector using push_back()
void add()
{
cout<<"Enter the no items to add : "; cin>>n;
for(i=0;i<n;i++)
{
cout<<"Number "<<(i+1)<<" : "; cin>>ele;
db.push_back(ele);
}
}
// display the elements in vector using indexing
void disp()
{
unsigned int i;
cout<<"Total elements in Vector(Resizable Array) :"<<db.size()<<"\n";

Containers in C++ Page 6


| C++ Containers

for(i=0;i<db.size();i++)
{
cout<<" "<<db[i]<<"\n";
}
}
// pop the elements from end of the vector using pop_back()
void del()
{
int i,ch=0;
cout<<"Enter no of elements to delete : ";
cin>>ch;
if(ch>n)
cout<<"List Index out of range...";
else
{
for(i=0;i<ch;i++)
db.pop_back();
cout<<ch<<" elements are successfully deleted...\n";
cout<<"Do u want to see the elements : press yes /no : ";
cin>>user;
if(strcmp(user,"yes")==0||strcmp(user,"YES")==0)
{
cout<<"------------------------------------------------------\n";
cout<<" \n"; cout<<"\t\tData Retrieval in Vector\n";
disp();
}
}
}
};

Containers in C++ Page 7


| C++ Containers

int main()
{
cout<<"=========================================\n";
cout<<"\t\tVector (Dynamic Array)\n";
cout<<"=========================================\n";
DynamicArray obj;
cout<<"\t\tInsertion in Vector\n";
obj.add();
cout<<"\t\tData Retrieval in Vector\n";
cout<<"------------------------------------------------------\n";
obj.disp();
cout<<"\t\tDeletion in Vector\n";
cout<<"------------------------------------------------------\n";
obj.del();
cout<<"------------------------------------------------------\n";
return 0;
}

Containers in C++ Page 8


| C++ Containers

OUTPUT

Containers in C++ Page 9


| C++ Containers

LIST (DOUBLY LINKED LIST)


• List is a dynamic array in c++ and available in the header file <list>
• It provides a doubly linked list. It allows for fast insertion and deletion
operations in the list
• Like array, it is used to store the elements of a specified type
• Unlike vector, it does not support indexing. So, elements can be
retrieved using iterator object.
• It provides iterator to traverse the list in both forward and reverse
(backward direction) directions.
Required Header File
#include<list>
Syntax
list<type> name;

Where,

• Type can be any base types like int, char*, float, char, bool, etc,
Example

list<int> ld;

IMPORTANT METHODS OF LIST CLASS


1. push_back(ele)
• It is an instance method of list class
• It is used to add the elements of specified type to end of the list
• It takes only one argument which is a particular type like int / float /
char etc,.
• Return type: void

Containers in C++ Page 10


| C++ Containers

2. push_front(ele)
• It is an instance method of list class
• It is used to add the elements of specified type to front of the list
• It takes only one argument which is a particular type like int / float /
char etc,.
• Return type: void
3. pop_back()
• It is an instance method of list class
• It is used to remove the top element (last element) from the list
• It does not take any arguments
• Return type: void
4. pop_front()

• It is an instance method of list class


• It is used to remove the first element from the list
• It does not take any arguments
• Return type: void
5. size()

• It is an instance method of list class


• It is used to display or return the total number of elements in the list
• Return type: int

Containers in C++ Page 11


| C++ Containers

III. EXAMPLE OF LIST (BACK END)


Language : C++
Type of Container : Sequential Container
Container Used : List
OS : Windows
IDE : Code Blocks
SOURCE CODE
#include<iostream>
#include<string.h>
#include<list>
using namespace std;
class Linkedlist
{
public:
// define list container
list<int> no;
list<int>::iterator ii;
int i,n,ele;
char user[100];
// add elements to end of the linked list using push_back()
void add()
{
cout<<"Enter the no items to add : "; cin>>n;
for(i=0;i<n;i++)
{
cout<<"Index "<<(i+1)<<" : "; cin>>ele;
no.push_back(ele);
}
Containers in C++ Page 12
| C++ Containers

}
// pop the elements from end of the linked list (Back End) using
pop_back()
void del()
{
int i,ch=0;
cout<<"Enter no of elements to delete : "; cin>>ch;
if(ch>n)
cout<<"List Index out of range...";
else
{
for(i=0;i<ch;i++)
no.pop_back();
cout<<ch<<" elements are successfully deleted from top...\n";
cout<<"Do u want to see the elements : press yes /no : ";
cin>>user;
if(strcmp(user,"yes")==0||strcmp(user,"YES")==0)
{
cout<<"----------------------------------------------------\n";
disp();
}
}
}
void disp()
{
cout<<"Total elements in Linked List : "<<no.size()<<"\n";
for(ii=no.begin();ii!=no.end();ii++)
{
cout<<"->"<<*ii;
}
Containers in C++ Page 13
| C++ Containers

cout<<endl;
}
};
int main()
{
cout<<"====================================\n";
cout<<"\tList STL(Linked List) at BACK End\n";
cout<<"====================================\n";
Linkedlist obj;
obj.add();
cout<<"----------------------------------------------------\n";
obj.disp();
cout<<"----------------------------------------------------\n";
obj.del();
cout<<"----------------------------------------------------\n";
return 0;
}

Containers in C++ Page 14


| C++ Containers

OUTPUT

Containers in C++ Page 15


| C++ Containers

IV. EXAMPLE OF LIST (FRONT END)


Language : C++
Type of Container : Sequential Container
Container Used : List
OS : Windows
IDE : Code Blocks
SOURCE CODE
#include<iostream>
#include<list>
#include<string.h>
using namespace std;
class Linkedlist
{
public:
// define list container
list<int> no;
list<int>::iterator ii;
int i,n,ele;
char user[100];
// add elements to begin of the linked list using push_front()
void add()
{
cout<<"Enter the no items to add : "; cin>>n;
for(i=0;i<n;i++)
{
cout<<"Index "<<(i+1)<<" : "; cin>>ele;
no.push_front(ele);
}
Containers in C++ Page 16
| C++ Containers

}
// display the elements in linked list
void disp()
{
cout<<"Total elements in Linked List : "<<no.size()<<"\n";
for(ii=no.begin();ii!=no.end();ii++)
{
cout<<"->"<<*ii;
}
cout<<endl;
}
// pop the elements from front of the linked list using pop_front()
void del()
{
int i,ch=0;
cout<<"Enter no of elements to delete : "; cin>>ch;
if(ch>n)
cout<<"List Index out of range...";
else
{
for(i=0;i<ch;i++)
{
no.pop_front();
}
cout<<ch<<" elements are successfully deleted...\n";
cout<<"Do u want to see the elements : press yes /no : ";
cin>>user;
if(strcmp(user,"yes")==0||strcmp(user,"YES")==0)
{

Containers in C++ Page 17


| C++ Containers

cout<<" \n";
disp();
}
}
}
};
int main()
{
cout<<"==========================================\n";
cout<<"\tList STL(Linked List) at FRONT End\n";
cout<<"==========================================\n";
Linkedlist obj;
obj.add();
cout<<"---------------------------------------------------\n";
obj.disp();
cout<<"---------------------------------------------------\n";
obj.del();
cout<<"---------------------------------------------------\n";
return 0;
}

Containers in C++ Page 18


| C++ Containers

OUTPUT

Containers in C++ Page 19


| C++ Containers

II. ASSOCIATIVE CONTAINERS


• Unlike sequential containers, these are used to store the elements in
the sorted order.
• Examples:
▪ Set
▪ Map
▪ Multiset
▪ Multimap
SET
• It is a data structure which is used to store the unique elements in
sorted order
• It does not accept the duplicate elements
• Set is created using the reserved keyword set and it is available on
#include<set> header file
• Unlike vector, it does not support indexing
• Elements in the set can be displayed using two ways
▪ Using Iterator
▪ Using ranged for loop
IMPORTANT METHODS OF SET CONTAINERS
1. insert(ele)
• This is the instance method of the set
• It is used to insert an element in the set
• This will take one or more number of arguments where first argument
is the element of the specific type of set
• Return type: iterator
2. size()
• This is the instance method of the set
• It is used to display the total number of elements in set as integer
• Return type: void

Containers in C++ Page 20


| C++ Containers

3. begin()
• This is the instance method of the set
• It is used to return an iterator which is the beginning of the set (address
of the first element in the set)
• Return type: iterator
4. end()
• This is the instance method of the set
• It is used to return an iterator which is the ending of the set (address of
the last element in the set)
• Return type: iterator
5. clear()
• It is an instance method of the set
• It is used to remove all the elements from set
• Return type: void
6. empty()
• It is an instance method of the set
• It is used to check whether the set is empty or not
• Return type: bool

Containers in C++ Page 21


| C++ Containers

1. EXAMPLE OF SET CONTAINER


SOURCE CODE
#include<iostream>
#include<set>
using namespace std;
int main()
{
cout<<"------------------------------------------------\n";
cout<<"\t Associative Containers - Set\n";
cout<<"------------------------------------------------\n";
// define set with specified type
set<int> db={81,12,33,44,55,66};
// display the elements in set using ranged for loop like java
cout<<"Elements in Set (Sorted Order):\n";
cout<<"------------------------------------------------\n";
for(int i:db)
{
cout<<" "<<i<<"\n";
}
cout<<"------------------------------------------------\n";
return 18;
}

Containers in C++ Page 22


| C++ Containers

OUTPUT

2. EXAMPLE OF SET CONTAINER


(Insertion, Deletion, Retrieval)
SOURCE CODE
#include<iostream>
#include<set>
#include<string>
using namespace std;
void disp()
{
// declare the set
set<string> db;
set<string>::iterator ii;
// add the elements to set using insert() method
db.insert("Good Morning");
db.insert("Hello World");
db.insert("Have a Nice Day");
db.insert("Welcome to C++");
db.insert("Welcome to Linux");
Containers in C++ Page 23
| C++ Containers

db.insert("Welcome to Java");
// remove particular element
db.erase("Hello World");
cout<<"\t Displaying Elements using Iterator\n";
cout<<"-------------------------------------------------------------\n";
// display the contents using iterator
for(ii=db.begin();ii!=db.end();ii++)
{
cout<<*ii<<" "<<"\n";
}
cout<<"\n";
// delete all the elements
db.clear();
cout<<"Elements after Deletion:\n";
cout<<"-------------------------------------------------------------\n";
if(db.size()!=0)
{
for(auto d:db)
{
cout<<d<<"\n";
}
}
else
{
cout<<"Set is empty\n";
}

Containers in C++ Page 24


| C++ Containers

int main()
{
cout<<"--------------------------------------------\n";
cout<<"\t Set Data Structure\n";
cout<<"--------------------------------------------\n";
disp();
return 5;
}

OUTPUT

Containers in C++ Page 25


| C++ Containers

MAP
• It is a data structure which is used to store the key value elements in
the sorted order
• Here key does not accept the duplicate elements. It should be
unique. But value can accept duplicate elements
• Map is created using the reserved keyword map followed by { {k1,v1},
..{kn,vn}} and it is available on #include<set> header file
• Elements in the map can be displayed using two ways
▪ Using Iterator
▪ Using ranged for loop
IMPORTANT METHODS AND PROPERTIES OF MAP CONTAINER
1. insert({key, value})
• This is the built-in instance method of the map
• It is used to insert an key-value pair of elements in the map
• This will take one or more number of arguments where first argument
is the key value pair of elements of the specific type of map
• Return type: iterator
2. size()
• This is the built-in instance method of the set
• It is used to display the total number of key-value pair of elements in
map as integer
• Return type: void
3. begin()
• This is the built-in instance method of the map
• It is used to return an iterator which is the beginning of the map
(address of the first element in the map)
• Return type: iterator

Containers in C++ Page 26


| C++ Containers

4. end()
• This is the built-in instance method of the set
• It is used to return an iterator which is the ending of the set (address of
the last element in the set)
• Return type: iterator
5. clear()
• It is an instance method of the map
• It is used to remove all the key-value pair of elements from map
• Return type: void
6. empty()
• It is an instance method of the map
• It is used to check whether the map is empty or not
• Return type: bool
7. at()
• It is an instance method of the map
• It is used to return a reference to the value associated with the given
key
• Return type: const mapped_type &
8. operator[index key]
• It is the operator [] followed by index position which is the key of the
map
• It is used to return a reference to the value associated with the given
key
• Return: const mapped_type &

Containers in C++ Page 27


| C++ Containers

3. EXAMPLE OF MAP CONTAINER


SOURCE CODE
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
cout<<"------------------------------------------------\n";
cout<<"\t Associative Containers - Map\n";
cout<<"------------------------------------------------\n";
// define map with int as key and string as value
map<int,string> mb={{1,"Ram"},{15,"Peter"},{3,"Mani"},{12,"Rohit"}};
// display the elements in set using ranged for loop like java
cout<<"Elements in Set (Sorted Order):\n";
cout<<"------------------------------------------------\n";
// display the elements in map using ranged for loop
// auto is keyword which is used to hold the value without knowing its
data type which is similar to python
for(auto [k,v]:mb)
{
cout<<k<<"\t->\t"<<v<<"\n";
}
cout<<"------------------------------------------------\n";
return 18;
}

Containers in C++ Page 28


| C++ Containers

OUTPUT

III. UNORDERED ASSOCIATIVE CONTAINERS


• This is the unordered version of associative containers.
• Internally these containers are implemented as hash table data
structures
• Unlike associative containers, these are used to store the elements in
the sorted order.
• Examples:
▪ Unordered Set
▪ Unordered Map
▪ Unordered Multiset
▪ Unordered Multimap

Containers in C++ Page 29


| C++ Containers

1. EXAMPLE OF UNORDERED ASSOCIATIVE CONTAINERS –


UNORDERED SET
SOURCE CODE
#include<iostream>
#include<unordered_set>
using namespace std;
int main()
{
cout<<"------------------------------------------------------\n";
cout<<"\t Unordered Associative Containers - Set\n";
cout<<"------------------------------------------------------\n";
// define unordered set data structure
unordered_set<int> db={11,33,55,44,81};
// display the elements in unordered set using ranged for loop like java
cout<<"Elements in Unordered Set :\n";
cout<<"------------------------------------------------------\n";
for(int i:db)
{
cout<<" "<<i<<"\n";
}
cout<<"------------------------------------------------------\n";
return 18;
}

Containers in C++ Page 30


| C++ Containers

OUTPUT

Containers in C++ Page 31


| C++ Containers

C++ CONTAINER ADAPTERS


• In c++, container adapters provide the restricted interface using the
existing STL containers.
TYPES OF CONTAINER ADAPTERS
• Stack
• Queue
• Priority Queue
1. STACK
• Stack is a first in last out or last in first out (FILO) data structure
• It will store and delete the elements using common end which is called
as top
• Required header file:
▪ #include<stack>
IMPORTANT METHODS
1. push(ele)
• This is the instance method of stack adapter
• This method is used to add the element at the top of the stack
• Return type: void
2. pop()
• This is the instance method of stack adapter
• It is used to remove the top element of the stack
• It does not take any argument
• Return type: void
3. top()
• This is the instance method of stack adapter
• This method is used to display the top element from the stack
• Return type: const_reference

Containers in C++ Page 32


| C++ Containers

4. size()
• This is the instance method of stack adapter
• This method is used to display the total number of elements in the
stack
• Return type: size_type
5. empty()
• This is the instance method of stack adapter
• It is used to check whether the stack is empty or not
• Return type: bool

Containers in C++ Page 33


| C++ Containers

I. EXAMPLE OF STACK DATA STRUCTURE


SOURCE CODE
#include<iostream>
#include<stack>
using namespace std;
int main()
{
cout<<"-----------------------------------------------\n";
cout<<"\t C++ Stack Container Adapter\n";
cout<<"-----------------------------------------------\n";
// create stack of specific type
stack<int> db;
// store the elements to stack
db.push(35);
db.push(51);
db.push(77);
cout<<"Total Number of Elements in stack: "<<db.size()<<"\n";
// display the elements of stack using empty(), top and pop() methods
while(db.empty()!=true)
{
cout<<" "<<db.top()<<" "<<"\n";
db.pop();
}
cout<<"------------------------------------------------\n";
return 5;
}

Containers in C++ Page 34


| C++ Containers

OUTPUT

2. QUEUE
• Unlike stack, it is first in first out data structure
• It uses two ends where,
▪ Rear end is used for adding the elements at the back of queue
▪ Front end is used for removing the elements from the front of
queue.
• Required Header File
▪ #include<queue>
• Example – Ration Queue

Containers in C++ Page 35


| C++ Containers

IMPORTANT METHODS
1. push(ele)
• This is the instance method of queue adapter
• This method is used to add the element at the end of the queue or
back of the queue (rear end)
• Return type: void
2. pop()
• This is the instance method of queue adapter
• It is used to remove the element at the front of the queue (front end)
• It does not take any argument
• Return type: void
3. front()
• This is the instance method of queue adapter
• This method is used to return or display the first element of the queue
• Return type: const_reference
4. back()
• This is the instance method of queue adapter
• This method is used to return or display the last element of the queue
• Return type: const_reference
5. size()
• This is the instance method of queue adapter
• This method is used to display the total number of elements in the
queue
• Return type: size_type
6. empty()
• This is the instance method of queue adapter
• It is used to check whether the queue is empty or not
• Return type: bool

Containers in C++ Page 36


| C++ Containers

II. EXAMPLE OF QUEUE DATA STRUCTURE


SOURCE CODE
#include<iostream>
#include<queue>
using namespace std;
int main()
{
cout<<"-----------------------------------------------\n";
cout<<"\t C++ Queue Container Adapter\n";
cout<<"-----------------------------------------------\n";
// create queue of specific type
queue<string> db;
// store the elements to queue at the back end (rear)
db.push("Chennai");
db.push("Salem");
db.push("Trichy");
db.push("Madurai");
db.push("Delhi");
cout<<"Total Number of Elements in Queue: "<<db.size()<<"\n";

// display the elements of queue using empty(), top and pop() methods
while(db.empty()!=true)
{
// display (return) the first element of queue
cout<<" "<<db.front()<<" "<<"\n";
// remove the element from queue (front end)
db.pop();
}
cout<<"------------------------------------------------\n";

Containers in C++ Page 37


| C++ Containers

return 5;
}

OUTPUT

3. PRIORITY QUEUE
• It is extended version of normal queue
• It is a type of STL container which consider only the highest priority
element
• Queue follows the FIFO order for displaying elements while priority
queue follows the priority order for displaying elements
• It is used to display the elements based on the highest priority
(highest priority element is popped first)
• If two or more number of elements exists with same priority then, the
order of element in the queue will be taken into consideration
• Required Header File
▪ #include<queue>

Containers in C++ Page 38


| C++ Containers

III. EXAMPLE OF PRIORITY QUEUE


SOURCE CODE
#include<iostream>
#include<queue>
using namespace std;
int main()
{
cout<<"----------------------------------------------------------\n";
cout<<"\t C++ Priority Queue Container Adapter\n";
cout<<"----------------------------------------------------------\n";
// create priority queue of specific type
priority_queue<int> pq;
// store the elements to priority queue at the back end (rear)
pq.push(23);
pq.push(51);
pq.push(12);
pq.push(45);
pq.push(92);
cout<<"Total Number of Elements in Priority Queue: "<<pq.size()<<"\n";
cout<<"Displaying Elements based on Top Priority\n";
cout<<"----------------------------------------------------------\n";
// display the elements of queue using empty(), top() and pop()
methods
int i=1;
while(pq.empty()!=true)
{
// display (return) the top element from the priority queue
cout<<" "<<pq.top()<<" -> "<<"Order "<<i++<<"\n";
// remove the element from queue (front end)
pq.pop();
Containers in C++ Page 39
| C++ Containers

}
cout<<"----------------------------------------------------------\n";
return 5;
}

OUTPUT

Containers in C++ Page 40

You might also like