std::vector
¶#include <vector>
#include <iostream>
template <typename T>
void printVector (const std::vector<T>& v) {
// traditional for-loop
for (size_t i = 0; i < v.size(); ++i) {
std::cout << v[i] << ' ';
}
std::cout << '\n';
}
template <typename T>
void printVector2 (std::vector<T> const& v) {
// range-based for-loop
for (auto val : v) {
std::cout << val << ' ';
}
std::cout << '\n';
}
template <typename T>
void addFourByValue(std::vector<T> vec, T value) {
vec.push_back(value);
vec.push_back(value);
vec.push_back(value);
vec.push_back(value);
}
template <typename T>
void addFourByRef(std::vector<T>& vec, T value) {
vec.push_back(value);
vec.push_back(value);
vec.push_back(value);
vec.push_back(value);
}
std::vector
¶std::vector<int> a {1, 5, 2, 4, 7};
printVector(a);
1 5 2 4 7
a.push_back(15);
printVector(a);
1 5 2 4 7 15
a.erase(a.begin());
printVector2(a);
5 2 4 7 15
std::vector<int> b (a.end() - 3, a.end());
printVector2(b);
4 7 15
addFourByValue(b, 12);
printVector(b);
4 7 15
addFourByRef(b, 12);
printVector(b);
4 7 15 12 12 12 12
std::cout << "b.at(14) is " << b.at(14) << '\n';
b.at(14) is
Standard Exception: vector::_M_range_check: __n (which is 14) >= this->size() (which is 7)
std::cout << "b[14] is " << b[14] << '\n';
b[14] is 81
std::vector
¶std::vector<int> d;
d
{}
std::cout << "size: " << d.size() << '\n';
std::cout << "capacity: " << d.capacity() << '\n';
std::cout << "data ptr: "<< d.data() << '\n';
std::cout << std::endl;
for (int i = 0; i < 10; ++i) {
d[i] = 4;
}
d
size: 0 capacity: 0 data ptr: 0
std::vector<int> e(10);
e
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
std::cout << "size: " << e.size() << '\n';
std::cout << "capacity: " << e.capacity() << '\n';
std::cout << "data ptr: "<< e.data() << '\n';
for (int i = 0; i < 10; ++i) {
e[i] = 4;
}
e
size: 10 capacity: 10 data ptr: 0x55eff6cd7fc0
{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }
push_back
¶std::vector<int> f;
std::cout << "size: " << f.size() << '\n';
std::cout << "capacity: " << f.capacity() << '\n';
std::cout << "data ptr: "<< f.data() << '\n';
f
size: 0 capacity: 0 data ptr: 0
{}
for (int i = 0; i < 10; ++i) {
f.push_back(4);
}
std::cout << "size: " << f.size() << '\n';
std::cout << "capacity: " << f.capacity() << '\n';
std::cout << "data ptr: "<< f.data() << '\n';
f
size: 10 capacity: 16 data ptr: 0x55eff7045770
{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }