STL is just a name/acronym for Standard Template Library. What is it? It is a library of classes that are actually class templates and are present under ‘std’ namespace. That means these libraries come with C++ by default.
Like printf is a standard function, vector is a standard class template.
The important class templates I’ll write about are:
- vector
- list
- set
- map
All of these classes are derived from one class called container class. As the name suggests the container classes contain one or more objects that may represent a data structure. In other words, container classes are wrapper over certain data structures and make a programmers life easier as he/she doesn’t need to write every time complex data structures.
You need to use std:: or using namespace std to use all of them
Vector – #include <vector>
It is a wrapper over a dynamic array and has methods to facilitate the allocating, deallocating or resizing the array with ease. Programmer doesn’t need to care about the different implementations with respect to array!
vector<string> v;
v.push_back("one");
v.push_back("two");
for (vector<string>::iterator iter = v.begin(); iter != v.end(); ++iter)
{
cout << *iter << endl;
}
List – #include <list>
Like vector, list is also a container class but the internally its not an array but a linked list. A programmer needs to carefully choose among different container types based on the use of it.
list<string> l;
l.push_back("one");
l.push_back("two");
for (list<string>::iterator iter = l.begin(); iter != l.end(); ++iter)
{
cout << *iter << endl;
}
Set – #include <set>
set<string> s;
s.insert("one");
s.insert("one"); // <-- This line will not affect the set... set doesn't let duplicate element to be inserted
s.insert("two");
You can iterate over the set like in the vector and list
Map – #include <map>
map<string, pair<int, int> > m;
m.insert(pair<string, pair<int, int> >("create", pair<int, int>(0, 124)));
m.insert(pair<string, pair<int, int> >("create", pair<int, int>(125, 203))); // <-- This line will not affect the map... map doesn't let duplicate **key** to be inserted.
m.insert(pair<string, pair<int, int> >("modify", pair<int, int>(125, 203)));
for (map<string, pair<int, int> >::iterator iter = m.begin(); iter != m.end(); ++iter)
{
// cout << *iter << endl; <-- This is a compiler error...
// A vector is an array of elements so type of *iter in case of vector returns an element which is actually string in the above vector example
//Same stands true with list and set too... you push_back or insert a string in all above cases...
//But in case of map you insert a pair<type1, type2> where type1 is string and type2 is pair<int, int>. In case of map iter is a composite object that looks like
// struct IterType {
// type1 first;
// type2 second;
//}
// So how do you print
cout << iter->first << endl;
// cout << iter->second << endl; <-- Now, this will give an error! I think I should leave it to you understanding why this will give an error
}