Dynamic Array
Arrays have a fixed size. Vectors / Dynamic Arrays can change in sizes. In C++, the vector library exists for a variable size array, but not in C.
C++ Vector
The following code creates a vector with five elements:
Another way to create a vector is to give the number of elements and the initial value for each element:
Other Useful vector APIs
Dynamic Array
Dynamic arrays are arrays allocated on the heap.
Content of freshly allocated array is garbage unless initialized with () or {} that default to 0.
To free dynamic array:
Difference with static array (ex: int arr[10]
)
- Static arrays are allocated on the stack.
- Static arrays size must be fixed (compile time constant).
Time Complexity of Dynamic Arrays#card
- Indexing:
- Search:
- Insertion:
- Deletion:
- Optimized Search:
2D Array
If you want to specify the directions, you can do the following:
Miscallaneous
emplace_back
vs. push_back
?
This is good nuance
Links:
- https://stackoverflow.com/questions/4303513/push-back-vs-emplace-back
- https://en.cppreference.com/w/cpp/container/vector/emplace_back
For emplace_back
, constructor A (int x_arg)
 will be called.
For push_back
, A (int x_arg)
 is called first and move A (A &&rhs)
 is called afterward.