Introduction to std::vector
std::vector
Intro vector
Intro
C++'s default
dynamic array
- array = can hold different values/objects of same type
- dynamic = size can be changed at runtime
This is a short introduction as part of the
Beginner's Guide To C++
.
If you are looking for a more complete interface overview with
guidelines, best practices and common mistakes please refer to
this page
.
#include <vector>
#include <iostream>
int main () {
using std::cout;
std::vector<int> v {2, 7, 9};
cout << v.size() << '\n';
cout << v[0] << '\n';
cout << v[1] << '\n';
v[1] = 4;
cout << v[1] << '\n';
cout << v.front() << '\n';
cout << v.back() << '\n';
}
Careful!
vector<T>::push_back(Element)
adds an element of type T
at the end of the vector
#include <iostream>
#include <vector>
int main () {
using std::cout;
std::vector<int> v;
cout << v.size() << '\n';
v.push_back(2);
cout << v.size() << '\n';
v.push_back(7);
cout << v.size() << '\n';
v.push_back(9);
cout << v.size() << '\n';
}
-
0
- 2
1
- 2
- 7
2
- 2
- 7
- 9
3
Resizing
vector<T>::resize(new_sizenew_number_of_elements, fillfiller_value=T{})
#include <iostream>
#include <vector>
int main () {
using std::cout;
std::vector<int> v {1,2};
v.push_back(3);
cout << v.size() << '\n';
v.resize(6, 0);
cout << v.size() << '\n';
}
- 1
- 2
- 1
- 2
- 3
3
- 1
- 2
- 3
- 0
- 0
- 0
6
Erasing Elements (at the end) Erasing (at the end) Erasing
vector<T>::pop_back()
vector<T>::clear()
#include <iostream>
#include <vector>
int main () {
using std::cout;
std::vector<int> v {1,2,3,4,5,6};
cout << v.size() <<'\n';
v.pop_back();
cout << v.size() <<'\n';
v.pop_back();
cout << v.size() <<'\n';
v.clear();
cout << v.size() <<'\n';
}
- 1
- 2
- 3
- 4
- 5
- 6
6
- 1
- 2
- 3
- 4
- 5
-
5
- 1
- 2
- 3
- 4
-
-
4
-
-
-
-
-
-
0
vector
is a so-called regular type, i.e.,
it behaves like int
in the following ways:
int
- deep copying: copying creates a new vector object and copies all contained objects
- deep assignment: all contained objects are copied from source to assignment target
- deep comparison: comparing two vectors compares the values of the contained objects
- deep ownership: destroying a vector destroys all contained objects
Most types in the C++ standard library and ecosystem are regular.
#include <iostream>
#include <vector>
int main () {
using std::cout;
std::vector<int> a {1,2,3,4};
std::vector<int> b = a; // copy a → b
if (a == b) cout << "equal\n";
a[0] = 9;
cout << b[0] <<'\n';
if (a != b) cout << "different\n";
}
a: - 1
- 2
- 3
- 4
b: - 1
- 2
- 3
- 4
equal
a: - 9
- 2
- 3
- 4
b: - 1
- 2
- 3
- 4
1
different
Be aware that copying vectors can be quite expensive (= take a long time) if they contain many elements (or the contained type is expensive to copy)!