• Register
100 points
7 2
Welcome to Kodlogs, programming questions and answer website.

Vectors are good to have in C++ programming language. They are very similar to arrays except the fact that we can resize them according to our needs. The nerd definition of vector is “vectors are sequence containers that can change their size according to the insertion or deletion of elements.”

How to print vectors?
 

Now we know about vectors and the relation in between arrays and vectors. Vectors requires a unique method to print its element as an array. 
 

Methods

  1. Using indices
  2. copy
  3. Iteration
  • Iteration

We can iterate over the vectors to print its elements. We iterate from the beginning to the end of the vector.

#include <iostream>
#include <vector>

void print(std::vector<int> const &input)
{
	for (auto it = input.cbegin(); it != input.cend(); it++)
	{
		std::cout << *it << ' ';
	}
}

int main()
{
	std::vector<int> input = { 1, 2, 3, 4, 5 };
	print(input);

	return 0;
}
  • Indices

Print elements using indices is like the traditional method of printing arrays in a program. We just have to iterate through elements of the vector. For iteration we use for-loop.

#include <iostream>
#include <vector>

void print(std::vector<int> const &input)
{
	for (int i = 0; i < input.size(); i++) {
		std::cout << input.at(i) << ' ';
	}
}

int main()
{
	std::vector<int> input = { 1, 2, 3, 4, 5 };
	print(input);

	return 0;
}
  • Copy

As the name suggests copying. We are going to copy the elements of the vector to the console or screen with the help of std::ostream_iterator.

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

void print(std::vector<int> const &input)
{
	std::copy(input.begin(),
			input.end(),
			std::ostream_iterator<int>(std::cout, " "));
}

int main()
{
	std::vector<int> input = { 1, 2, 3, 4, 5 };
	print(input);

	return 0;
}

Output

1 2 3 4 5
 

Hope this helps.

100 points
7 2