Standard Template Library - HackerEarth
Standard Template Library - HackerEarth
Notes 4
LIVE EVENTS
Standard Template Library
191 Stl CodeMonk
C++ Templates
Templates are a feature of the C++ programming language that allows functions and classes
to operate with generic types. This allows a function or class to work on many di erent data
types without being rewritten for each one.
The way we use normal parameters to pass as a value to function, in the same manner
template parameters can be used to pass type as argument to function. Basically, it tells
what type of data is being passed to the function.
Here, ‘type’ is just a placeholder used to store the data type when this function is used you
can use any other name instead class is used to specify the generic type of template,
alternatively typename can be used instead of it.
Assume we have to swap two variables of int type and two of oat type. Then, we will have
to make two functions where one can swap int type variables and the other one can swap
oat type variables. But here if we use a generic function, then we can simply make one
function and can swap both type of variables by passing their di erent type in the
arguments. Let’s implement this:
#include <iostream>
using namespace std ;
// creating a generic function ‘swap (parameter-list)’ using template
:
template <class X>
void swap( X &a, X &b) {
X tp;
tp = a;
a = b;
b = tp;
cout << " Swapped elements values of a and b are " << a << " 4
LIVE EVENTS
and " << b << " respectively " << endl;
}
int main( ) {
int a = 10, b = 20 ;
float c = 10.5, d = 20.5 ;
swap(a , b); // function swapping ‘int’
elements
swap(c , d); // function swapping ‘float’
elements
return 0;
}
Output :
After creating the generic function, compiler will automatically generate correct code for the
type of data used while executing the function.
C++ STL also has some containers (pre-build data structures) like vectors, iterators, pairs etc.
These are all generic class which can be used to represent collection of any data type.
Iterator
An iterator is any object that, points to some element in a range of elements (such as an
array or a container) and has the ability to iterate through those elements using a set of
operators (with at least the increment (++) and dereference (*) operators).
A pointer is a form of an iterator. A pointer can point to elements in an array, and can
iterate over them using the increment operator (++). There can be other types of iterators
as well. For each container class, we can de ne iterator which can be used to iterate
through all the elements of that container.
Example:
For Vector:
For List:
String
C++ provides a powerful alternative for the char*. It is not a built-in data type, but is a 4
container class in the Standard Template Library. String class provides di erent string
LIVE EVENTS
manipulation functions like concatenation, nd, replace etc. Let us see how to construct a
string type.
string s0; // s0 = “”
string s1(“Hello”); // s1 = “Hello”
string s2 (s1); // s2 = “Hello”
string s3 (s1, 1, 2); // s3 = “el”
string s4 ("Hello World", 5); // s4 = “Hello”
string s5 (5, ‘*’); // s5 = “*****”
string s6 (s1.begin(), s1.begin()+3); // s6 = “Hel”
LIVE EVENTS
size(): Returns the length of the string. Its time complexity is O(1).
substr(): Returns a string which is the copy of the substring. Its time complexity is O(N)
where N is the size of the substring.
Implementation:
#include <iostream>
#include <cstdio>
int main()
{
string s, s1;
s = "HELLO";
s1 = "HELLO";
if(s.compare(s1) == 0)
cout << s << " is equal to " << s1 << endl;
else
cout << s << " is not equal to " << s1 << endl;
s.append(" WORLD!");
cout << s << endl;
printf("%s\n", s.c_str());
if(s.compare(s1) == 0)
cout << s << " is equal to " << s1 << endl;
else
cout << s << " is not equal to " << s1 << endl;
return 0;
}
Output:
Vector
Vectors are sequence containers that have dynamic size. In other words, vectors are
dynamic arrays. Just like arrays, vector elements are placed in contiguous storage location
so they can be accessed and traversed using iterators. To traverse the vector we need the
position of the rst and last element in the vector which we can get through begin() and
end() or we can use indexing from 0 to size(). Let us see how to construct a vector.
vector<int> a; // empty 4
LIVE EVENTS
vector of ints
vector<int> b (5, 10); // five
ints with value 10
vector<int> c (b.begin(),b.end()); // iterating
through second
vector<int> d (c); // copy of c
Traverse:
void traverse(vector<int> v)
{
vector <int>::iterator it;
for(it = v.begin();it != v.end();++it)
cout << *it << ‘ ‘;
cout << endl;
for(int i = 0;i < v.size();++i)
cout << v[i] << ‘ ‘;
cout << endl;
} 4
LIVE EVENTS
Implementation:
#include <iostream>
#include <vector>
int main()
{
vector <int> v;
vector <int>::iterator it;
v.push_back(5);
while(v.back() > 0)
v.push_back(v.back() - 1);
for(it = v.begin(); it != v.end();++it)
cout << *it << ' ';
cout << endl;
for(int i = 0;i < v.size();++i)
cout << v.at(i) << ' ';
cout << endl;
while(!v.empty())
{
cout << v.back() << ' ';
v.pop_back();
}
cout << endl;
return 0;
}
Output:
5 4 3 2 1 0
5 4 3 2 1 0
0 1 2 3 4 5
List
List is a sequence container which takes constant time in inserting and removing elements.
List in STL is implemented as Doubly Link List.
The elements from List cannot be directly accessed. For example to access element of a
particular position ,you have to iterate from a known position to that particular position.
//declaration 4
LIVE EVENTS
list <int> LI;
Implementation:
#include <iostream>
#include <list>
using namespace std;
int main()
{
list <int> LI;
list <int>::iterator it;
//inserts elements at end of list 4
LIVE EVENTS
LI.push_back(4);
LI.push_back(5);
LIVE EVENTS
return 0;
}
Output:
Pair
Pair is a container that can be used to bind together a two values which may be of di erent
types. Pair provides a way to store two heterogeneous objects as a single unit.
We can also initialize a pair using make_pair() function. make_pair(x, y) will return a pair
with rst element set to x and second element set to y.
p1 = make_pair(2, ‘b’);
To access the elements we use keywords, rst and second to access the rst and second
element respectively.
Implementation:
#include <iostream>
#include <utility>
int main()
{
pair <int, char> p;
pair <int, char> p1(2, 'b');
p = make_pair(1, 'a');
cout << p.first << ' ' << p.second << endl;
cout << p1.first << ' ' << p1.second << endl; 4
LIVE EVENTS
return 0;
}
Output:
1 a
2 b
Sets
Sets are containers which store only unique values and permit easy look ups. The values in
the sets are stored in some speci c order (like ascending or descending). Elements can only
be inserted or deleted, but cannot be modi ed. We can access and traverse set elements
using iterators just like vectors.
Traverse:
void traverse(set<int> s)
{
set <int>::iterator it;
4
for(it = s.begin();it != s.end();++it)
LIVE EVENTS
cout << *it << ‘ ‘;
cout << endl;
}
Implementation:
#include <iostream>
#include <set>
int main()
{
set <int> s;
set <int>::iterator it;
int A[] = {3, 5, 2, 1, 5, 4};
for(int i = 0;i < 6;++i)
s.insert(A[i]);
for(it = s.begin();it != s.end();++it)
cout << *it << ' ';
cout << endl;
return 0;
}
Output:
1 2 3 4 5
Maps
Maps are containers which store elements by mapping their value against a particular key. It
stores the combination of key value and mapped value following a speci c order. Here key
value are used to uniquely identify the elements mapped to it. The data type of key value
and mapped value can be di erent. Elements in map are always in sorted order by their
corresponding key and can be accessed directly by their key using bracket operator ([ ]).
In map, key and mapped value have a pair type combination,i.e both key and mapped value
can be accessed using pair type functionalities with the help of iterators.
//declaration. Here key values are of char type and mapped values(value of element) is of
int type.
map <char ,int > mp;
mp[‘b’] = 1;
4
LIVE EVENTS
It will map value 1 with key ‘b’. We can directly access 1 by using mp[ ‘b’ ].
mp[‘a’] = 2;
Implementation:
#include <iostream>
#include <map>
using namespace std;
int main(){
map <char,int> mp;
map <char,int> mymap,mymap1;
LIVE EVENTS
'mymap'.
mymap.insert(mp.begin(),mp.end());
LIVE EVENTS
{
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
Output:
LIVE EVENTS
Stacks:
Stack is a container which follows the LIFO (Last In First Out) order and the elements are
inserted and deleted from one end of the container. The element which is inserted last will
be extracted rst.
Declaration:
stack <int> s;
Implementation:
#include <iostream>
#include <stack>
//size of stack s
cout<<”Size of stack is: ” <<s.size( )<<endl;
LIVE EVENTS
s.pop( );
}
if(s.empty())
{
cout <<”Stack is empty.”<<endl;
}
else
{
cout <<”Stack is Not empty.”<<endl;
}
return 0;
Output:
Queues:
Queue is a container which follows FIFO order (First In First Out) . Here elements are
inserted at one end (rear ) and extracted from another end(front) .
Declaration:
queue <int> q;
Implementation:
#include <iostream>
#include <cstdio>
#include <queue>
4
LIVE EVENTS
using namespace std;
int main() {
char qu[4] = {'a', 'b', 'c', 'd'};
queue <char> q;
int N = 3; // Number of steps
char ch;
for(int i = 0;i < 4;++i)
q.push(qu[i]);
for(int i = 0;i < N;++i) {
ch = q.front();
q.push(ch);
q.pop();
}
while(!q.empty()) {
printf("%c", q.front());
q.pop();
}
printf("\n");
return 0;
}
Output:
dabc
Priority Queue:
A priority queue is a container that provides constant time extraction of the largest element,
at the expense of logarithmic insertion. It is similar to the heap in which we can add
element at any time but only the maximum element can be retrieved. In a priority queue,
an element with high priority is served before an element with low priority.
Declaration:
priority_queue<int> pq;
LIVE EVENTS
top(): Returns a reference to the largest element in the priority queue. Its time complexity is
O(1).
Implementation:
#include <iostream>
#include <queue>
int main()
{
priority_queue<int> pq;
pq.push(10);
pq.push(20);
pq.push(5);
while(!pq.empty())
{
cout << pq.top() << endl;
pq.pop();
}
return 0;
}
Output:
20
10
5
Solve Problems
Like 3 Tweet
Join Discussion...
Post
Cancel
LIVE EVENTS
posting this suggestion. If I am wrong then ignore this because I am a beginner. While I was
reading I tried to run your very rst code of "FUNCTION TEMPLATES" ,compiler was showing
an error "ambiguous call to function swap" because there also a function std::swap and
when we are using namespace std, compiler doesn't understand which function your are
referring to i.e to your de ned "swap" function or "std::swap" function. To tackle this
situation either we can remove using namespace std; but that would make our life harder as
we need to write "std" each time we use functions from "std" namespace so, the other
solution is to change the function name, this would be the an easiest solution.
5 votes Reply Message Permalink
at that point v.back() is equal to 5. v.back() will return the value of the last element.
0 votes Reply Message Permalink
hey @akash i was a bit confused in handling tuples.. Can u explain that as well.. ? They are a
bit di erent from the usual containers
0 votes Reply Message Permalink
Tuples are immutable containers in which you can store values of di erent types. You
can only store things in them but you cannot update it. You can access them using
get<>.
0 votes Reply Message Permalink
Thanks. Edited :)
0 votes Reply Message Permalink
Pallav Mittal 2 years ago
LIVE EVENTS
Thanks Pallav :)
Good Luck for the contest
0 votes Reply Message Permalink
Thanks :)
I am glad that it helped you to learn STL. Good Luck for the contest.
0 votes Reply Message Permalink
Hi Akash,
In String member function
length(): Returns the length of the string. Its time complexity is O(N) where N is the size of
the string.
size(): Returns the length of the string. Its time complexity is O(1).
What is di ernence between these two function ?
http://stackover ow.com/questions/905479/stdstring-length-and-size-member-functions
This stackover ow answer say that there is no di erence, then why the time complexity is
di erent for those function?
0 votes Reply Message Permalink
Thanks Shubham :)
0 votes Reply Message Permalink
Awesome post
0 votes Reply Message Permalink
Thanks Ashutosh :)
Thanks Ashutosh :)
0 votes Reply Message Permalink
In the vector section, the end() function is described as returning the pointer to the last 4
element in the vector. If that is taken to be true then the code that iterates over the vector
LIVE EVENTS
should not print the last element as the loop termination condition given is " it!= v.end() "
BUT the output shows the last element
0 votes Reply Message Permalink
very informative.
0 votes Reply Message Permalink
Thanks Ram :)
0 votes Reply Message Permalink
For the Stack Code, the output would include 'The Stack is Empty' too :)
0 votes Reply Message Permalink
Are these the only data structures which we need to know in STL?
0 votes Reply Message Permalink
Its because I am using a template. Using template you can only swap same data types.
You can't swap di erent data types.
0 votes Reply Message Permalink
I am not sure but the rst example of swaping a generic type itself is failing 4
LIVE EVENTS
0 votes Reply Message Permalink
Very clear and to the point explanation of concept of templates and its built in provisions in
c++.
Thank you.
0 votes Reply Message Permalink
The code for template class in the very beginning doesn't compile. Is it right or am I missing
something???
0 votes Reply Message Permalink
Can you please explain : If we want to insert elements in decreasing order in sets and how
to set priority of element by own for di erent programs?
0 votes Reply Message Permalink
priority_queue<int,vector<int>,greater<int> >q;
now insert the element in the q;
0 votes Reply Message Permalink
LIVE EVENTS
Thank you soooo much for this great tutorial.If you don't mind i am facing a lot of problem
in dp . Can you help me Plz ...I know it is not right place to ask but i am impressed with your
tutorial so i thought you are the right person to guide.
0 votes Reply Message Permalink
I want to make a priority queue of pair<int ,int>, where priority is set by the greatest second
element of pair ,can anyone help?
0 votes Reply Message Permalink
AUTHOR
Akash Sharma
Problem Curator at Hacker…
Dehradun
7 notes
4
LIVE EVENTS
TRENDING NOTES
Press Careers
Reach Us