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).
1 2 3 4 5 |
#include <vector> int main() { std::vector<int> my_vector {1, 2, 3, 4, 5}; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <vector> int main() { std::vector<int> my_vector {1, 2, 3, 4, 5}; // create an iterator for the vector std::vector<int>::iterator itr; // iterate over the vector and print each element for (itr = my_vector.begin(); itr != my_vector.end(); ++itr) { std::cout << *itr << " "; } std::cout << std::endl; } |
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.