C++ Print Vector Elements

To print elements of C++ vector, you can use any of the looping statements or foreach statement.

Print Vector Elements using ForEach

In the following program, we shall use C++ Foreach statement to print the elements of vector.

C++ Program

#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<int> nums;
   nums.push_back(53);
   nums.push_back(47);
   nums.push_back(85);
   nums.push_back(92);

   for (int element: nums)
      cout << element << endl;
}

Output

53
47
85
92

Print Vector Elements using While Loop

In the following program, we shall use C++ While Loop to print the elements of vector from starting to end. We shall use index to access an element of vector during each iteration.

C++ Program

#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<int> nums;
   nums.push_back(53);
   nums.push_back(47);
   nums.push_back(85);
   nums.push_back(92);

   int i = 0;
   while (i < nums.size()) {
      cout << nums[i] << endl;
      i++;
   }     
}

Output

53
47
85
92

Print Vector Elements using For Loop

In the following program, we shall use C++ For Loop to print the elements of vector. As in while loop, we shall use index to access elements of vector in this example as well.

C++ Program

#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<int> nums;
   nums.push_back(53);
   nums.push_back(47);
   nums.push_back(85);
   nums.push_back(92);

   for (int i = 0; i < nums.size(); i++) {
      cout << nums[i] << endl;
   }     
}

Output

53
47
85
92

Conclusion

In this C++ Tutorial, we learned how to print all the elements of a vector from start to end using loop statements and foreach statement.