How To Print Vector In C++ Using Iterator

Printing a vector in C++ is a common task that programmers encounter in their projects. There are different ways to print the elements of a vector, and one of them is by using an iterator. In this tutorial, we will learn how to print a vector in C++ using an iterator.

Steps:

1. Create a vector

The first step in printing a vector is to create one. We can do this by using the vector class from the C++ Standard Template Library (STL).

In this example, we created a vector called my_vector that contains integers 1 to 5.

2. Print the vector using an iterator

To print the elements of the vector using an iterator, we need to iterate over the container and print each element. We can use a for loop or a while loop to achieve this.

In this example, we created an iterator called itr for the vector using the begin and end functions. We then used a for loop to iterate over the vector and print each element using the *itr notation.

3. Run the program

After writing the code, we can run the program and see the output. The output should be the elements of the vector separated by spaces.

1 2 3 4 5

Conclusion:

Printing a vector using an iterator is a simple and effective way to display the elements of the container.

By creating an iterator and iterating over the vector, we can print each element using the *itr notation.

This method is useful when we need to print the contents of a vector in a formatted output.