C++ Dynamic Arrays
-
What is dynamic array
A dynamic array is quite similar to a regular array, but its size is modifiable during program runtime. It automatically grows when we try to make an insertion and there is no more space left for the new item. In C++ there is
std::vector
class that is dynamic array. -
How to use
std::vector
classTo create dynamic array we use
std::vector
class from#include <vector>
and then in<>
you specify data type that vector will contain.#include <vector> struct Entity{ float m_x, m_y; Entity(x, y) :m_x(x), m_y(y) {} }; std::vector<Entity> entities;
To add something to vector we use
push_back()
method. It creates an object and then copies it into vector.#include <vector> struct Entity{ float m_x, m_y; Entity(float x, float y) :m_x(x), m_y(y) {} }; std::vector<Entity> entities; entities.push_back(Entity(1, 2));
To erase from vector we use
erase()
method#include <vector> struct Entity{ float m_x, m_y; Entity(float x, float y) :m_x(x), m_y(y) {} }; std::vector<Entity> entities; entities.push_back(Entity(1, 2)); entities.push_back(Entity(2, 2)); entities.erase(entities.begin() + 1); // it will erase second element
If you know space you will need you can allocate space using
reserve()
method. It will boost performance because it won't need to resize vector.#include <vector> struct Entity{ float m_x, m_y; Entity(float x, float y) :m_x(x), m_y(y) {} }; std::vector<Entity> entities; entities.reserve(2); // you reserve space for 2 entities objects entities.push_back(Entity(1, 2)); entities.push_back(Entity(2, 2));
emplace_back()
method constructs object in place in memory where vector is. No copy will be made like withpush_back()
method. You dont pass constructor for object but you pass parameter list for the constructor.#include <vector> struct Entity{ float m_x, m_y; Entity(float x, float y) :m_x(x), m_y(y) {} }; std::vector<Entity> entities; entities.emplace_back(1, 2);