SlideShare a Scribd company logo
1 of 29
STL-Choosing Right
Containers
Sangharsh
Agarwal
Containers
• Sequential containers
– Vector
– Deque
– List
• Associative containers
– Set
– Map
– Multiset
– Multimap
• Container adaptors
– Stack
– Queue
– Priority queue
Memory allocation
Containers Memory Allocation
Vector Contiguous memory
allocation
Deque Memory allocated in chunks
List Node wise memory allocation
Map Binary tree (RGB)
Set Binary tree (RGB)
Multimap Binary tree (RGB)
MultiSet Binary tree (RGB)
Syntax of containers
• Vector
• Deque
• List
template < class T, class Allocator = allocator<T> >
class vector;
template < class T, class Allocator = allocator<T> >
class list;
template < class T, class Allocator = allocator<T> >
class deque;
• Set
• Where the template parameters have the following
meanings:
– Key: Key type: type of the elements contained in the
container. Each elements in a set is also its key.
– Compare: Comparison class. A class that takes two
arguments of the same type as the container
elements and returns a bool.
– Allocator: Type of the allocator object used to define
the storage allocation model. By default, the allocator
class template for type Key is used, which defines the
simplest memory allocation model and is value-
independent.
template < class Key, class Compare = less<Key>,
class Allocator = allocator<Key> > class set;
• Map
• Where the template parameters have the
following meanings:
– Key: Type of the key values. Each element in a map is
uniquely identified by its key value.
– T: Type of the mapped value. Each element in a map is
used to store some data as its mapped value.
– Compare: Comparison class.
– Allocator: Type of the allocator object used to define
the storage allocation model.
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key,T> > >
class map;
Usage of containers
Ayes of Vector
• If all you want is a "smart array" class that offers
random access to elements, and perhaps the
ability to append new elements to its end, then
vector is the right choice.
• Accessing individual elements by their position
index (constant time).
• Iterating over the elements in any order (linear
time).
• Add and remove elements from its end (constant
amortized time).
Ayes of Deque
• Deque, provides random access and the subscript
notation for accessing elements, just like vector. Yet
unlike vector, it supports efficient insertions and
deletions at both ends.
• Individual elements can be accessed by their position
index.
• Iteration over the elements can be performed in any
order.
• Elements can be efficiently added and removed from
any of its ends (either the beginning or the end of the
sequence).
• E.g. Operating system's scheduler.
Ayes of List
• Efficient insertion and removal of elements
anywhere in the container (constant time).
• If you don't need random access (say, "15
positions from the beginning" or "three positions
before the current element") and you do need to
insert new elements between existing elements
frequently, then list is a good choice.
• Efficient moving elements and block of elements
within the container or even between different
containers: splice operation (constant time).
• E.g. Window’s task manager
Ayes of Map
• As associative containers, they are especially
designed to be efficient accessing its elements
by their key (unlike sequence containers,
which are more efficient accessing elements
by their relative or absolute position).
• Unique key values: no two elements in the
map have keys that compare equal to each
other
• Each element is composed of a key and a
mapped value.
Ayes of Set
• Internally, the elements in a set are always sorted from
lower to higher following a specific strict weak ordering
criterion set on container construction.
• Unique element values: no two elements in the set
can compare equal to each other. For a similar
associative container allowing for multiple equivalent
elements, see multiset.
• The element value is the key itself. For a similar
associative container where elements are accessed
using a key, but map to a value different than this key,
see map.
Adaptors
• Adaptor containers change ordinary
containers such as vector and deque, making
them look as different container types.
• For example, a stack is usually implemented as
a list with a different interface. Instead
of push_back() and pop_back(), it
has push() and pop().
Stack
• Stack (declared in <stack> ) is an ideal choice
when you need to a LIFO data structure.
• For example, think about people entering the
back seat of a car that has only one door: the
last person to enter is the first to exit.
• The four basic operations that
a stack supports are push(), pop(),top(),
and empty().
Queue
• A queue (declared in <queue> ), or FIFO, is
characterized by having elements inserted into
one end and removed from the other end.
• For example: a queue of people at a theater's
box office.
• The queue adaptor container is implemented
in one of two ways: either as a deque or as
a list.
Note
• As a general rule, always check which unique
operations a certain container supports, and
which common operations it disables. These
should give you more than a hint regarding its
optimal usage.
Nays of containers
Nays of Vector
• When you find yourself, frequently inserting,
removing elements in the middle of the
vector.
• If you think about inserting elements before
the first element, then clearly vector is not the
right choice because it doesn't even have
a push_front() operation.
• Reallocation problem with vector.
• Let's see how this can happen. Suppose you have a
vector that has 256 elements:
vector <int> vi(256); //vi contains 256
int's
• At this point, you define an iterator that is pointing to
the first element like this:
for (vector<int>::iterator it=
vi.begin();...)
• Then, you call push_back() to insert a new element:
vi.push_back(99);
• From this moment, there's no guarantee that it is valid
because the push_back() call may have triggered
reallocation
Nays of List
• When is list a bad choice? First and foremost,
– When you need random access to elements.
– If you need to sort the elements frequently.
Although list does offer the sort()operation,
sorting lists isn't as efficient as sorting vectors.
Nays of Deque
• When you find yourself, frequently inserting,
removing elements in the middle of the
deque.
• Calling insert() in the middle of
the deque invalidates all the iterators and
references to its elements.
• Calling insert() at either end of the deque invalidates all
its iterators but has no effect on the validity of
references to its elements.
After the push_front() call, the iterator it becomes invalid whereas the pointer p remains
valid.
• Similarly, calling erase() in the middle of
the deque invalidates all the iterators and references to
its elements.
• Calling erase() at either end of the deque invalidates
only the iterators and the references to the erased
elements.
deque<int> di;
int p* = &di[5];
deque<int>::iterator
it=di.begin()+5; di.push_front(8);
Vector<bool> ?.......
• The vector class template has a special
template specialization for the bool type.
• This specialization is provided to optimize for
space allocation: In this template
specialization, each element occupies only
one bit (which is eight times less than the
smallest type in C++: char).
• The references to elements of a bool vector
returned by the vector members are not
references to bool objects, but a special
member type which is a reference to a single
bit, defined inside the vector<bool> class
specialization as:
class vector<bool>::reference {
friend class vector;
reference(); // no public
constructor
public:
~reference();
operator bool () const; // convert to bool
reference& operator= ( const bool x ); // assign from bool
reference& operator= ( const reference& x ); // assign from bit
void flip(); // flip bit value.
}
Summary
• If all you want is a "smart array" class that offers
random access to elements, and perhaps the ability to
append new elements to its end, then vector is the
right choice.
• When you need to insert or remove elements at either
end of a container frequently, but you rarely use
insertions and deletions in the middle, deque is a good
choice.
• If you don't need random access (say, "15 positions
from the beginning" or "three positions before the
current element") and you do need to insert new
elements between existing elements frequently,
then list is a good choice.
• As associative containers, they are especially
designed to be efficient accessing its elements
by their key (unlike sequence containers,
which are more efficient accessing elements
by their relative or absolute position).
FAQs?
• Why pop() returns void?
• Default container used to implement Stack
and queue?
References
• Effective STL (Scott Meyers)
• http://www.informit.com/guides/content.aspx
?g=cplusplus&seqNum=205
• http://www.gotw.ca/gotw/054.htm
• http://www.cplusplus.com/reference/stl/

More Related Content

What's hot

Standard template library
Standard template libraryStandard template library
Standard template librarySukriti Singh
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in PythonRaajendra M
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Python Dictionary
Python DictionaryPython Dictionary
Python DictionarySoba Arjun
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptxvishal choudhary
 
1 03 - CSS Introduction
1 03 - CSS Introduction1 03 - CSS Introduction
1 03 - CSS Introductionapnwebdev
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data StructureMeghaj Mallick
 
Queue implementation
Queue implementationQueue implementation
Queue implementationRajendran
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5IT Geeks
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Aijaz Ali Abro
 

What's hot (20)

sets and maps
 sets and maps sets and maps
sets and maps
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java script
Java scriptJava script
Java script
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 
Linked list
Linked listLinked list
Linked list
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
Linked list
Linked listLinked list
Linked list
 
Linked lists
Linked listsLinked lists
Linked lists
 
1 03 - CSS Introduction
1 03 - CSS Introduction1 03 - CSS Introduction
1 03 - CSS Introduction
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
Data Structures
Data StructuresData Structures
Data Structures
 

Similar to How to choose best containers in STL (C++)

Similar to How to choose best containers in STL (C++) (20)

Javasession7
Javasession7Javasession7
Javasession7
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
Dynamic memory allocation and linked lists
Dynamic memory allocation and linked listsDynamic memory allocation and linked lists
Dynamic memory allocation and linked lists
 
Java util
Java utilJava util
Java util
 
oops_final_ppt[1].pptx
oops_final_ppt[1].pptxoops_final_ppt[1].pptx
oops_final_ppt[1].pptx
 
DS Module1 (1).pptx
DS Module1 (1).pptxDS Module1 (1).pptx
DS Module1 (1).pptx
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Acm aleppo cpc training seventh session
Acm aleppo cpc training seventh sessionAcm aleppo cpc training seventh session
Acm aleppo cpc training seventh session
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptx
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
 
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxAssg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
 
java.pdf
java.pdfjava.pdf
java.pdf
 
Unit 2 linear data structures
Unit 2   linear data structuresUnit 2   linear data structures
Unit 2 linear data structures
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 

Recently uploaded

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 

Recently uploaded (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

How to choose best containers in STL (C++)

  • 2. Containers • Sequential containers – Vector – Deque – List • Associative containers – Set – Map – Multiset – Multimap • Container adaptors – Stack – Queue – Priority queue
  • 3. Memory allocation Containers Memory Allocation Vector Contiguous memory allocation Deque Memory allocated in chunks List Node wise memory allocation Map Binary tree (RGB) Set Binary tree (RGB) Multimap Binary tree (RGB) MultiSet Binary tree (RGB)
  • 5. • Vector • Deque • List template < class T, class Allocator = allocator<T> > class vector; template < class T, class Allocator = allocator<T> > class list; template < class T, class Allocator = allocator<T> > class deque;
  • 6. • Set • Where the template parameters have the following meanings: – Key: Key type: type of the elements contained in the container. Each elements in a set is also its key. – Compare: Comparison class. A class that takes two arguments of the same type as the container elements and returns a bool. – Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type Key is used, which defines the simplest memory allocation model and is value- independent. template < class Key, class Compare = less<Key>, class Allocator = allocator<Key> > class set;
  • 7. • Map • Where the template parameters have the following meanings: – Key: Type of the key values. Each element in a map is uniquely identified by its key value. – T: Type of the mapped value. Each element in a map is used to store some data as its mapped value. – Compare: Comparison class. – Allocator: Type of the allocator object used to define the storage allocation model. template < class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key,T> > > class map;
  • 9. Ayes of Vector • If all you want is a "smart array" class that offers random access to elements, and perhaps the ability to append new elements to its end, then vector is the right choice. • Accessing individual elements by their position index (constant time). • Iterating over the elements in any order (linear time). • Add and remove elements from its end (constant amortized time).
  • 10. Ayes of Deque • Deque, provides random access and the subscript notation for accessing elements, just like vector. Yet unlike vector, it supports efficient insertions and deletions at both ends. • Individual elements can be accessed by their position index. • Iteration over the elements can be performed in any order. • Elements can be efficiently added and removed from any of its ends (either the beginning or the end of the sequence). • E.g. Operating system's scheduler.
  • 11. Ayes of List • Efficient insertion and removal of elements anywhere in the container (constant time). • If you don't need random access (say, "15 positions from the beginning" or "three positions before the current element") and you do need to insert new elements between existing elements frequently, then list is a good choice. • Efficient moving elements and block of elements within the container or even between different containers: splice operation (constant time). • E.g. Window’s task manager
  • 12. Ayes of Map • As associative containers, they are especially designed to be efficient accessing its elements by their key (unlike sequence containers, which are more efficient accessing elements by their relative or absolute position). • Unique key values: no two elements in the map have keys that compare equal to each other • Each element is composed of a key and a mapped value.
  • 13. Ayes of Set • Internally, the elements in a set are always sorted from lower to higher following a specific strict weak ordering criterion set on container construction. • Unique element values: no two elements in the set can compare equal to each other. For a similar associative container allowing for multiple equivalent elements, see multiset. • The element value is the key itself. For a similar associative container where elements are accessed using a key, but map to a value different than this key, see map.
  • 14. Adaptors • Adaptor containers change ordinary containers such as vector and deque, making them look as different container types. • For example, a stack is usually implemented as a list with a different interface. Instead of push_back() and pop_back(), it has push() and pop().
  • 15. Stack • Stack (declared in <stack> ) is an ideal choice when you need to a LIFO data structure. • For example, think about people entering the back seat of a car that has only one door: the last person to enter is the first to exit. • The four basic operations that a stack supports are push(), pop(),top(), and empty().
  • 16. Queue • A queue (declared in <queue> ), or FIFO, is characterized by having elements inserted into one end and removed from the other end. • For example: a queue of people at a theater's box office. • The queue adaptor container is implemented in one of two ways: either as a deque or as a list.
  • 17. Note • As a general rule, always check which unique operations a certain container supports, and which common operations it disables. These should give you more than a hint regarding its optimal usage.
  • 19. Nays of Vector • When you find yourself, frequently inserting, removing elements in the middle of the vector. • If you think about inserting elements before the first element, then clearly vector is not the right choice because it doesn't even have a push_front() operation.
  • 20. • Reallocation problem with vector. • Let's see how this can happen. Suppose you have a vector that has 256 elements: vector <int> vi(256); //vi contains 256 int's • At this point, you define an iterator that is pointing to the first element like this: for (vector<int>::iterator it= vi.begin();...) • Then, you call push_back() to insert a new element: vi.push_back(99); • From this moment, there's no guarantee that it is valid because the push_back() call may have triggered reallocation
  • 21. Nays of List • When is list a bad choice? First and foremost, – When you need random access to elements. – If you need to sort the elements frequently. Although list does offer the sort()operation, sorting lists isn't as efficient as sorting vectors.
  • 22. Nays of Deque • When you find yourself, frequently inserting, removing elements in the middle of the deque. • Calling insert() in the middle of the deque invalidates all the iterators and references to its elements.
  • 23. • Calling insert() at either end of the deque invalidates all its iterators but has no effect on the validity of references to its elements. After the push_front() call, the iterator it becomes invalid whereas the pointer p remains valid. • Similarly, calling erase() in the middle of the deque invalidates all the iterators and references to its elements. • Calling erase() at either end of the deque invalidates only the iterators and the references to the erased elements. deque<int> di; int p* = &di[5]; deque<int>::iterator it=di.begin()+5; di.push_front(8);
  • 24. Vector<bool> ?....... • The vector class template has a special template specialization for the bool type. • This specialization is provided to optimize for space allocation: In this template specialization, each element occupies only one bit (which is eight times less than the smallest type in C++: char).
  • 25. • The references to elements of a bool vector returned by the vector members are not references to bool objects, but a special member type which is a reference to a single bit, defined inside the vector<bool> class specialization as: class vector<bool>::reference { friend class vector; reference(); // no public constructor public: ~reference(); operator bool () const; // convert to bool reference& operator= ( const bool x ); // assign from bool reference& operator= ( const reference& x ); // assign from bit void flip(); // flip bit value. }
  • 26. Summary • If all you want is a "smart array" class that offers random access to elements, and perhaps the ability to append new elements to its end, then vector is the right choice. • When you need to insert or remove elements at either end of a container frequently, but you rarely use insertions and deletions in the middle, deque is a good choice. • If you don't need random access (say, "15 positions from the beginning" or "three positions before the current element") and you do need to insert new elements between existing elements frequently, then list is a good choice.
  • 27. • As associative containers, they are especially designed to be efficient accessing its elements by their key (unlike sequence containers, which are more efficient accessing elements by their relative or absolute position).
  • 28. FAQs? • Why pop() returns void? • Default container used to implement Stack and queue?
  • 29. References • Effective STL (Scott Meyers) • http://www.informit.com/guides/content.aspx ?g=cplusplus&seqNum=205 • http://www.gotw.ca/gotw/054.htm • http://www.cplusplus.com/reference/stl/