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);
a.push_back(15);
printVector(a);
a.erase(a.begin());
printVector2(a);
std::vector<int> b (a.end() - 3, a.end());
printVector2(b);
addFourByValue(b, 12);
printVector(b);
addFourByRef(b, 12);
printVector(b);
std::cout << "b.at(14) is " << b.at(14) << '\n';
std::cout << "b[14] is " << b[14] << '\n';
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
std::vector<int> e(10);
e
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
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
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