vector structure c++ code example

Example 1: vector c++

Vectors are sequence container that can change size. Container is a objects 
that hold data of same type. Sequence containers store elements strictly in 
linear sequence.

Vector stores elements in contiguous memory locations and enables direct access
to any element using subscript operator []. Unlike array, vector can shrink or
expand as needed at run time. The storage of the vector is handled automatically.

To support shrink and expand functionality at runtime, vector container may 
allocate some extra storage to accommodate for possible growth thus container
have actual capacity greater than the size. Therefore, compared to array, vector
consumes more memory in exchange for the ability to manage storage and grow 
dynamically in an efficient way.

Zero sized vectors are also valid. In that case vector.begin() and vector.end()
points to same location. But behavior of calling front() or back() is undefined.

Example 2: c++ vector structure

#include <vector>

typedef struct test1 {
  int a;
  char b;
} TOTO;

std::vector<TOTO> _v;

_v.push_back((TOTO){10, 'a'});
_v[0].a = 101;

Tags:

Cpp Example