Introduction To Vectors in C++ Word PDF
Introduction To Vectors in C++ Word PDF
Fall 2020-2021
EECE 330
Data Structures and Algorithms
Guidelines
This tutorial consists of three parts.
After you finish each part, solve the problems associated with it.
About vectors
A vector is in many ways similar to dynamic arrays in C++.
Unlike arrays, it has the ability to resize itself automatically if elements are added or deleted
to the vector.
They can also be accessed/traversed with iterators.
Vector elements are placed in contiguous storage. They are as efficient as arrays but consume
more memory due to their storage management and dynamic growth.
To declare a vector and initialize it with a number of elements equal to an initial value:
// vector <type> name (number of elements, initial value);
vector <int> v1(5, 18);
index: 0 1 2 3 4
v1[index]: 18 18 18 18 18
index: 0 1 2 3 4
v2[index]: 3 5 6 0 202
To get an iterator pointing to the (theoretical) element after the last element of a vector, we use:
vec.end();
The functions above are typically used in a for/while loop as in the example below which prints all
the elements in the vector.
vector<int> g1;
...
for (vector<int>::iterator it = g1.begin(); it != g1.end(); ++it)
cout << *it << " ";
Alternatively, we can use the placeholder auto to automatically deduce the type of the variable.
for (auto it = g1.begin(); it != g1.end(); ++it)
cout << *it << " ";