STL(vector, list, map)
0. Overview:
STL is the soul of C++. Remember this, mastering the STL is master the most part of C++. Though array is more efficient than vector, vector is still the feature of C++. In this sector, we will discuss the basic usage of vector, list, and map. Simply explain these three STL. Vector is array with intelligent memory allocation/deallocation, which saves us from the size of container; List can be regarded as doubly linked list, specific feature will be covered in the code; Map is hash table, which will be frequently used in algorithm problem.
1. Vector:
Vector is advanced type of array, because vector has more flexible way to
handle problem.
It has member function: size(), front(), end(), push_back(T t), pop_back().
Also, besides the traditional way to iterate the container, you could user iterator in STL to do this.
// vector<int>: vector of int
// vector<vector<int>>: vector of (vector of int)
// vector<int *>: the vector of pointers to int
// vector<vector<int> *>: vector of pointers to vector of int
// vector
vector<int> V1 {
3, 4, 5, 6, 7};
// 5 5 3 7
cout << V1.size() << " " << V1[2] << " " << V1.front() << " " << V1.back() << endl;
// 10 elements; all with initial value 3
vector<int> V2(10, 3);
// 6 elements; all with initial value 0
vector<int> V3(6);
// add new element 8 to the back of the vector
V1.push_back(8);
//remove the last element of the vector
V1.pop_back();
// print the vector
// call by value
// 3 4 5 6 7 8
for(int i : V1){
cout << i << " "; i++; }
cout << endl;
// The same as above
// 3 4 5 6 7 8
for(int i : V1){
cout << i << " "; }
cout << endl;
// call by reference
// 3 4 5 6 7 8
for(int &i : V1){
cout << i << " "; i++; }
cout << endl;
// 4 5 6 7 8 9
for(int i : V1){
cout << i << " "; }
cout << endl;
// Iterator
// begin() returns the address of the first element
// endI() returns the address AFTER the last element
vector<int>::iterator it1 = V1.begin(), it2 = V1.end();
auto it3 = V1.begin();
for(auto it6 = V1.begin(); it6 != V1.end(); it6++){
cout << *it6 << " ";
}
auto it10 = V1.begin() + 10;
// auto can be very handful
// map<int , vector<list<int*> *>:: iterator it5 = M1.begin();
// auto it5 = M