Programming/C++/Objects and Data Structures
< Programming | C++
Jump to navigation
Jump to search
Basic Data Structures
Vectors
A vector is a C++ simple class, that effectively acts as a "dynamic array".
It is technically slower and takes more space, but it can be arbitrary sizes.
Creating Vectors
#include <vector> # Create empty vector. std::vector<<data_type>> <vector_name>; # Create vector with some initial data. std::vector<<data_type>> <vector_name> = {<data_value_1>, <data_value_2>}; # Create vector with some number of elements, but elements aren't populated yet. std::vector<<data_type>> <vector_name>(<number_of_elements>);
Ex:
#include <vector> # Create empty vector. std::vector<int> my_int_vector; # Create vector with some initial data. std::vector<int> my_int_vector = {95, 12, 29}; # Create vector with some number of elements, but elements aren't populated yet. # In this case, 5 elements. std::vector<int> my_int_vector(5);
Manipulating Vectors
Get vector length:
<vector_var>.size();
Get item at vector index:
... # Get vector item at a given index. <vector_var>[<index>];
Ex:
... # Get vector item at a given index. # In this case, we get the 6th item, located at index 5 (vectors start at index 0). my_int_vector[5];
Add item to vector:
... # Add item to end of vector. <vector_var>.push_back(<value>); # Insert item at given vector index. <vector_var>.insert(<index>, <value>);
Remove item from vector:
... # Remove item from end of vector (no return value). <vector_var>.pop_back(); # Remove item at given vector index. <vector_var>.remove(<index>);