I am studying the basics of C++ Standard Template Library (or STL) to improve my abilities to solve more competitive programming problems.
Here we'll start with Vector and see how we can use its features.
Vector
If you've already played with arrays in another language (or even in C/C++), you have a pretty good idea about STL Vector. It is a container that can store elements, but its size can change dynamically (C/C++ array's size do not change dynamically).
Let's start with the initialization. We can store int, string, float elements, depending on how we initialize the vector. We'll play with integer numbers first.
vector<int> v;
You did it! Pretty simple!
Now we can store some random integer numbers. The magic method is "push_back".
vector<int> v;
v.push_back(2);
v.push_back(5);
v.push_back(1);
v.push_back(3);
v.push_back(4);
Now we have 5 numbers stored in our vector:
If we use pop_back(), we'll remove the last element.
v.pop_back();
To remove the first element, we can use erase(). We need to pass the element's position(iterator position), we want to remove , as an argument.
v.erase(v.begin());
We can also remove the last element using erase()*.
v.erase(v.begin() + v.size() - 1);
Do you wang the first element? Use front.
v.front();
Do you want the last element? Use back.
v.back();
Do you want to know the number of elements inside the vector? Use size.
v.size();
Instead of using
v.size() == 0;
use the empty method (see interesting reason.
v.empty();
As a simple array, we can use the ***[]***and the = operator.
v[0] = 10;
v[1] = 20;
v[2] = 30;
cout<< v[0] <<endl; // 10
cout<< v[1] <<endl; // 20
cout<< v[2] <<endl; // 30
Let's remove all elements from this vector.
v.clear();
We can use algorithm's sort to order the vector elements in an ascending order.
#include <algorithm>
sort(v.begin(), v.end());
And in a descending order, using the greater<int> comparison as the third argument.
#include <algorithm>
sort(v.begin(), v.end(), greater<int>());
Imagine that you don't want to write
"sort(v.begin(), v.end(), greater
We can put this code into a void function, passing the vector as an argument. So now the question is: "How can we pass the vector as an argument?". And we have two ways:
1. As a reference:
void desc_sort(vector<int> &v) {
sort(v.begin(), v.end(), greater<int>());
}
desc_sort(v);
2. As a pointer
void desc_sort(vector<int> *v) {
sort(v->begin(), v->end(), greater<int>());
}
desc_sort(&v);
That's it!