Initialization:
#include <vector> #include <stdexcept> ... typedef std::vector<int> IntVector; ... size_t size = 3; IntVector array(size);
Access:
// No bound controll: Access to uninitialized memory !! // for (unsigned int i = 0; i < (size + 1); i++) { // array[i] = i; // } // Bound control -> vector::_M_range_check for (unsigned int i = 0; i < (size + 1); i++) { try { array.at(i) = i; } catch(std::out_of_range e) { std::cout << e.what() << std::endl; } } // array.size() = 3; array.capacity = 3;
Add:
// Add elements beyond the initial size array.push_back(9); // array.size() = 4; array.capacity = 6; for (unsigned int i = 0; i < array.size(); i++) { std::cout << array[i] << std::endl; // {0, 1, 2, 9} }
From C arrays to C++ Vector:
int p[] = {1, 2, 3, 4, 5}; IntVector a(p, p+5); for (unsigned int i = 0; i < a.size(); i++) { std::cout << a[i] << std::endl; // {1, 2, 3, 4, 5} }
Iterator:
IntVector vector; IntVector::const_iterator i; vector.push_back(1); vector.push_back(2); vector.push_back(3); for (i = vector.begin(); i != vector.end(); i++) { std::cout << "(*i)" << (*i) << std::endl; }