A vector is like an array, but it can grow and shrink while the program runs. In modern C++, vectors are what you'll use most of the time. Add #include <vector>:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers = {10, 20, 30};
cout << "Size: " << numbers.size() << "\n";
numbers.push_back(40); // add to the end
numbers.push_back(50);
cout << "Size now: " << numbers.size() << "\n";
cout << "First: " << numbers[0] << ", last: " << numbers.back() << "\n";
numbers.pop_back(); // remove the last item
cout << "After pop_back the last is " << numbers.back() << "\n";
return 0;
}Output
Size: 3 Size now: 5 First: 10, last: 50 After pop_back the last is 40
The type in the angle brackets says what the vector holds: vector<int>, vector<double>, vector<string>...
Useful vector tools
| Code | What it does |
|---|---|
v.push_back(x) | add x to the end |
v.pop_back() | remove the last item |
v.size() | how many items |
v.empty() | true if there are no items |
v[i] | the item at index i |
v.at(i) | the same, but checks the index is valid |
v.front() / v.back() | first / last item |
v.clear() | remove everything |
Building a vector from input
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> values;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
values.push_back(x);
}
cout << "You entered " << values.size() << " numbers. The last was " << values.back() << ".\n";
return 0;
}Input (what the user types)
4 8 3 12 5
Output
You entered 4 numbers. The last was 5.
A vector of a certain size
vector<int> v(5, 0); makes 5 items that all start at 0. Great for counting things:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> votes(3, 0); // 3 candidates, 0 votes each
votes[1]++;
votes[1]++;
votes[2]++;
for (int i = 0; i < 3; i++) {
cout << "Candidate " << i << ": " << votes[i] << " votes\n";
}
return 0;
}Output
Candidate 0: 0 votes Candidate 1: 2 votes Candidate 2: 1 votes