Share
C++
Vectors are a useful data structure in C++
that act like dynamic one-dimensional arrays.
There are several ways to iterate through a vector.
vector<int> vec = {1, 2, 3, 4, 5};
for
loop and reference pointerIn C++
, vectors can be indexed with []operator
, similar to arrays.
To iterate through the vector, run a for
loop from i = 0
to i = vec.size()
.
#include <iostream>#include <vector>using namespace std;int main(){//decleration of int vectorvector<int> vec = {1, 2, 3, 4, 5};// returns length of vector as unsigned intunsigned int vecSize = vec.size();// run for loop from 0 to vecSizefor(unsigned int i = 0; i < vecSize; i++){cout << vec[i] << " ";}cout << endl;return 0;}
Instead of
[]operator
, theat()
function can also be used to fetch the value of a vector at a specific index:vec.at(i)
- Where
i
is the index.
iterator
An iterator
can be generated to traverse through a vector.
vector<int>::iterator iter;
An iterator
is used as a pointer
to iterate through a sequence such as a string
or vector
.
The pointer can then be incremented to access the next element in the sequence.
To access the value in the memory space to which the iterator is pointing, you must use *
.
#include <iostream>#include <vector>using namespace std;int main(){//decleration of int vectorvector<int> vec = {1, 2, 3, 4, 5};int vecSize = vec.size(); // returns length of vector//decleration of vector iteratorvector<int>::iterator iter = vec.begin();cout << "Vector: ";// run for loop from 0 to vecSizefor(iter; iter < vec.end(); iter++){// access value in the memory to which the pointer// is referencingcout << *iter << " ";}cout << endl;return 0;}
auto
keywordThe auto keyword can also be used to traverse through a vector.
auto
must be given a variable to store the accessed element and the sequence that needs to be iterated.
It must be used in conjunction with a for
loop, as shown below.
#include <iostream>#include <vector>using namespace std;int main() {//decleration of int vectorvector<int> vec = {1, 2, 3, 4, 5};int vecSize = vec.size(); // returns length of vectorcout << "Vector: ";for (auto & element : vec){cout << element << " ";}return 0;}