Skip to main content

C++ STL (Containers) Tutorial For Beginners Learn STL Hacks Part -2

In continuation of my STL tutorial series, I'll be introducing to some more STL containers in this post.


The containers I shall be covering include:

CONTAINERS

  • String Streams
  • Map
  • Multiset
  • Priority Queue


String Streams

Stringstream is the processing of input/output strings. The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings.
By treating the strings as streams we can perform extraction and insertion operation from/to string just like cin and cout streams.
C++ provides two interesting objects for it: ‘istringstream’ (input stringstream ) and ‘ostringstream’ (output stringstream). Both of these are declared in #include< stream >.


Object istringstream allows you to read from a string like you do from standard input. The ostringstream object is used to do formatting output.

Insertion And Extraction Operations Using stringstream

Insertion
(i) Using Insertion Operator (<<)
Data is assigned to stringstream buffer using << operator.

(ii)Using str(string) Function
Str function can also be used for assigning data to the stringstream buffer. The str function takes the data string as an argument and assigns this data to the stringstream object.

Extraction
(i) Using Extraction Operator (>>)
Stringsream data can be displayed using >> operator.

(ii)Using str() Function
We can use the str() function to get the data out of stringstream.

Demonstration of Insertion and Extraction Operators :
#include<bits/stdc++.h>
using namespace std;
int main()
{
//insertion operator <<
stringstream os; // string stream object os is created
os << "ankit rana ";
cout<<os.str();
//str(string) function to read input
os.str("testing the stringstream");
//str() function for extraction
cout<<os.str()<<endl;
//extraction operator (>>)
stringstream ss;
ss<<"11 05 2020";
// all the words will be extracted from string separated by space
string mystr1;
ss >> mystr1; //11
string mystr2;
ss>>mystr2; // 05
string mystr3;
ss>>mystr3; // 2020
cout<<mystr1<< "/"<<mystr2<<"/"<<mystr3;
cout<<"************** Happy Coding ***************";
}


Click Here Run and Check The Output Of Above Code

Map

Map is quite similar to set, except it contains not just values but pairsv<key, value>. Map ensures that at most one pair with specific key exists. Therefore, a map contains keys in a specific order and all the keys are unique with some value.Internally map and set are almost always stored as red-black trees.
Elements of map and set are always sorted in ascending by default.
Traversing map is easy with iterator, here iterator will be a pair of key and value. So, to get the value use ( it->first )  or ( it->second ).

Some Built-In Functions
  • begin(): Returns an iterator to the first element in the map.
  • size(): Returns the number of elements in the map.
  • empty(): Returns a boolean value indicating whether the map is empty.
  • insert( pair(key, value)): Adds a new key-value pair to the map. An alternate way to insert values in the map is:map_name[key] = value;
  • find(val): Gives the iterator to the element val, if it is found otherwise it returns m.end()
  • erase(iterator position): Removes the element at the position pointed by the iterator.
  • erase(const g): Removes the key value g from the map.
  • clear(): Removes all the elements from the map.
Implementation :

#include<bits/stdc++.h>
using namespace std;
int main()
{
// Initializing a map with integer keys
// and corresponding string values
map<int, string> Emp;
//Inserting values in map using insert function
Emp.insert ( pair<int, string>(101,"Jony") );
Emp.insert ( pair<int, string>(103,"Dan") );
Emp.insert ( pair<int, string>(104,"Aryan") );
// Inserting values using Array index notation
Emp[105] = "Sany";
Emp[102] = "Tyrio";
cout << "Size of the map is " << Emp.size() <<"\n\n";
// Printing values in the map
cout << endl << "Default Order of value in map:" <<"\n";
//first way to traverse map
cout<<"\nFirst Method Of Traversing Map :\n";
for( map<int,string>::iterator iter=Emp.begin(); iter!=Emp.end(); ++iter)
{
cout << (*iter).first << ": " << (*iter).second <<"\n";
}
//second way to traverse using auto
cout<<"\nSecond Method Of Traversing Map :\n";
for(auto &i : Emp)
cout<<i.first<<" : "<<i.second<<"\n";
// Finding the value corresponding to the key '102'
map<int, string>::iterator it = Emp.find(102);
if (it != Emp.end())
{
cout <<endl<< "Value of key = 102 => " << Emp.find(102)->second << '\n';
}
cout<<"************** Happy Coding ***************";
}
view raw map_ankit.cpp hosted with ❤ by GitHub


Click Here To Run the above code and check it's output

Multiset

Multisets are containers that store elements following a specific order, and where multiple elements can have equivalent values or there can be duplicate elements in it.
Implementation :

#include<bits/stdc++.h>
using namespace std;
int main() {
// declaration of a default multiset
multiset<int> asc;
// Inserting values into a multiset
asc.insert(1);
asc.insert(1);
asc.insert(6);
asc.insert(4);
asc.insert(10);
asc.insert(3);
//checking the output of this multiset
//using pointer
cout<<"Traversing Multiset Using Iterator :\n";
for(multiset<int> :: iterator it = asc.begin() ; it!=asc.end();it++)
cout<<(*it)<<" ";
//using auto
cout<<"\n\nTraversing Multiset Using Auto :\n";
for(auto &i : asc)
cout<<i<<" ";
//Declaration of a Multiset which stores element in descending order
multiset <int, greater <int> > desc;
// Inserting values into a multiset
desc.insert(1);
desc.insert(11);
desc.insert(10);
desc.insert(3);
desc.insert(4);
desc.insert(6);
desc.insert(8);
cout<<"\n\nTraversing Multiset Using Iterator :\n";
for(multiset<int> :: iterator it = desc.begin() ; it!=desc.end();it++)
cout<<(*it)<<" ";
//using auto
cout<<"\n\nTraversing Multiset Using Auto :\n";
for(auto &i : desc)
cout<<i<<" ";
cout<<"************** Happy Coding ***************";
return 0;
}
view raw multiset.cpp hosted with ❤ by GitHub

Click Here To Run & Check Output

Priority Queue

Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest/smallest of the elements it contains, according to some strict weak ordering criterion.
Priority Queue is used mostly in questions where the order of elements is either strictly increasing or decreasing. Insertions take place in a priority queue using push() function and deletion take place using pop(). 
Greatest/Smallest value element is always present on the top of the priority queue and pop() also deletes the element present on the top of priority queue.
Implementation

#include<bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int> max_heap; // declaration of priority_queue
max_heap.push(12); // inserting elements
max_heap.push(5);
max_heap.push(110);
max_heap.push(4);
max_heap.push(122);
max_heap.push(1);
max_heap.push(10);
cout<<"Elements of a Max Heap Priority Queue :\n";
priority_queue <int> temp = max_heap; // copy max_heap to temp
while (!temp.empty())// empty() checks if a container is empty or not
{
cout << '\t' << temp.top();
temp.pop(); // remove top from priority queue
}
cout << '\n';
priority_queue<int,vector<int>, greater<int> > min_heap; // declaration of priority_queue
min_heap.push(12); // inserting elements
min_heap.push(5);
min_heap.push(110);
min_heap.push(4);
min_heap.push(122);
min_heap.push(1);
min_heap.push(10);
cout<<"\n\nElements of a Min Heap Priority Queue :\n";
priority_queue <int,vector<int>,greater<int> > t = min_heap; // copy min_heap to t
while (!t.empty())// empty() checks if a container is empty or not
{
cout << '\t' << t.top();
t.pop(); // remove top from priority queue
}
cout << '\n';
cout<<"********** Happy Coding***********":
return 0;
}

Click Here To Run & Check Output

This is not the end of STL but the beginning... stay tuned for more stuff to come.
Happy Coding..!!

Comments

Most Popular Posts

Coding and Mathematics ( Importance Of Maths In Programming )

Everyone wants to become a good coder but only a few manage to achieve this you know why? BECAUSE everyone wants to code and no one really wants to be a good mathematician which is the basic requirement to be a coder, yet very few know this fact and try to be a  mathematician first than a coder. What exactly is coding? It is the process of solving different technical problems using a programming language. The technical problems can vary from printing a  simple "Hello World" program to solving "2 SAT Problem" using mathematics. You might today be able to solve a few problems using your technical skills but it would help you in the long run only if you're fundamentals of mathematics are also clear. By mathematics, I don't mean the whole of it but some important topics such as Discrete Math, Algebra, Number Theory, etc. Here are some concepts of mathematics that you will use mostly in solving the technical problems : Fundamentals B...

On Which Coding Platform Should I Practice?

Which is the best online platform to practice, how to improve my coding skills? This post is all about giving answers to all such questions. If you're a beginner who has got no idea what programming is then I would recommend you step by step practice any programming language on Hackerrank. Hackerrank has modules that are self-explanatory and would slowly make you understand all the terminologies which are generally used and with practice, you'll be better at it. Moreover, if you're still not able to understand anything you can always search for your answers on GeekForGeeks or HackerEarth both of them provide one of the best tutorials on any topic. If you're an intermediate who's comfortable with any programming language then you can always improve your problem-solving skills studying Data Structures and Algorithms and practicing it. You can also improve by competitive coding. The best place to start with competitive programming according to me would be ...

Symmetric and Identical Trees

In this blog, we're going to cover Symmetric Tree and Identical Tree problems. These are quite similar problems, in the Symmetric tree we are provided with a single tree, but for checking identical trees we're provided two trees. What is a Symmetric Tree? A tree is called symmetric if it contains a mirror image of itself when divided from the center(root). This means that the left portion of the tree should be symmetric to the right portion of the tree. Example of a Symmetric Tree: What are Identical Trees? Two trees are said to be identical when they have the same data and the arrangement of data is also the same in them. Example of Identical Trees: In symmetric trees, the left portion of the tree is compared to the right portion of the tree. Whereas in the case of identical trees the left portion of one tree is compared with the left portion of another tree similarly, the right portion of one tree is compared with the right portion of another tree. Implementation Symmetric Tr...