
An array's size is fixed from the start. A vector is a stretchy array — it grows and shrinks while running. For contest problems this is usually the better choice.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
cout << v.size() << endl; // 3
cout << v[1] << endl; // 20
for (int x : v) {
cout << x << " ";
}
cout << endl;
return 0;
}> what you see
3 20 10 20 30
//LINE BY LINE
Watch it run
vector<int> v; — empty. Not a single slot exists yet.
It grows while the program runs
Unlike an array, a vector's size does not have to be known in advance. push_back adds one to the end.
#include <vector>
vector<int> v; // хоосон
v.push_back(10);
v.push_back(20);
cout << v.size() << endl; // 2
cout << v[0] << endl; // 10> what you see
2 10
Useful operations
| You write | What it does |
|---|---|
v.push_back(x) | төгсгөлд нэмэх / add to the end |
v.size() | хэдэн элемент байгаа / how many elements |
v.empty() | хоосон эсэх / is it empty? |
v.clear() | бүгдийг арилгах / remove everything |
sort(v.begin(), v.end()) | эрэмбэлэх / sort it |
#include <algorithm>
vector<int> v = {5, 1, 4};
sort(v.begin(), v.end()); // 1 4 5
for (int x : v) cout << x << " ";> what you see
1 4 5