Home Icon Home Resource Centre How To Print A Vector In C++ | 8 Methods Explained With Examples

How To Print A Vector In C++ | 8 Methods Explained With Examples

A vector in programming is a container that stores elements of a given type and allows for random access when needed. It is important for programmers to know how to print a vector in C++ to write useful code.
Shivani Goyal
Schedule Icon 0 min read
How To Print A Vector In C++ | 8 Methods Explained With Examples
Schedule Icon 0 min read

Table of content: 

  • How To Print A Vector In C++ By Overloading Left Shift (<<) Operator?
  • How To Print Vector In C++ Using Range-Based For-Loop?
  • Print Vector In C++ With Comma Separator
  • Printing Vector In C++ Using Indices (Square Brackets/ Double Brackets & at() Function)
  • How To Print A Vector In C++ Using std::copy?
  • How To Print A Vector In C++ Using for_each() Function?
  • Printing C++ Vector Using The Lambda Function
  • How To Print Vector In C++ Using Iterators?
  • Conclusion
  • Frequently Asked Questions
expand

Vectors are similar to dynamic arrays, with the main difference being that the former are automatically resizable. Vector elements are stored in contiguous, i.e., continuous memory locations. This makes it easier to access and traverse through the vector elements using iterators or pointers. When the elements are added or removed from a vector, it is called insertion or deletion. To see the changes in the vector, we may need to print the vector elements.

In this article, we'll explore different methods of how to print a vector in C++, ranging from basic to advanced techniques. 

Mechanism of printing a vector in C++

Printing the elements of a vector is a common task in programming. There are multiple methods to get this done, as mentioned before. We have detailed each of these methods in the sections below with the help of C++ programs examples.

How To Print A Vector In C++ By Overloading Left Shift (<<) Operator?

Operator Overloading in C++ allows us to extend the abilities of an operator and give special meaning to it while keeping its original meaning intact. It can have the same name or symbol but more than one execution behavior or use.

How To Print A Vector In C++ | 8 Methods Explained With Examples

The output streams use the insertion operator ‘<<’ for standard types. To print all elements of the vector by iterating one by one, we need to overload the ‘<<’ operator. By overloading the << operator as a template function in the global scope, the cout can be made to accept a vector element after the ‘<<’ operator.

Here is an example of how to print a vector in C++ by overloading << operator:

Output:

U N S T O P

Explanation:

  1. The operator << is a template function that takes 2 arguments, the output stream (‘ostream& os) and the vector (‘constant vector<ele_type>& vector’). Here ele_type represents the type of elements in the vector.
  2. This function contains a for loop which iterates over each vector element, printed to the output stream, followed by a space.
  3. The function then returns the output stream to the calling function.
  4. In the main function, a vector V is initialized with character elements and object cout is used to print the elements of vector V by calling the operator << function.

How To Print Vector In C++ Using Range-Based For-Loop?

The range-based for-loop method is also another method that is widely used for printing vector elements in C++. We use an iterator to iterate through the full range or length of the vector. The iterator only iterates until the last element of the vector and therefore is dependent upon the vector size or range. This is hence referred to as the process of using range-based for-loop.

Given below is a sample code of how to print a vector in C++ using range-based for-loop:

Output:

Vector elements: 1 2 3 4 5

Explanation:

  1. We start by including the necessary header files. Here, iostream is required for input/output operations like std::cout, and vector is needed for using the std::vector container.
  2. In the main function, we declare a vector of integers named myVector and initialize it with five elements, 1, 2, 3, 4, and 5.
  3. We use std::cout to print the message Vector elements: on the console. This text will be displayed before the vector elements.
  4. Next, the program starts with the range-based for-loop.
  5. The loop iterates over the elements of myVector. The const auto& element declares a loop variable element, which will be assigned the value of each element in the vector during each iteration.
  6. Inside the loop, we use std::cout again to print the value of an element. Since the element represents each element in the vector during each iteration, this statement prints each element of the vector on the console, followed by a space.
  7. After the for-loop, we use std::cout to print std::endl, which adds a new line to move the cursor to the next line in the console. This ensures that the next output appears on a new line.
  8. Finally, the return 0; statement indicates that the main function has been successfully executed, and the program is terminating with no errors (returning 0 indicates successful completion).

Print Vector In C++ With Comma Separator

To avoid the overloading method, we can print the elements by making a custom separator function to print the elements by separating them using a separator. A comma operator (,) is a type of separator that is used while declaring, initializing variables, or defining elements in an array, vector, list, etc. Here we use the comma operator while printing.

Here is an example of how to print a vector in C++ using a separator function:

Output:

Print, Vector, Using, Comma, Separator,

Explanation:

  1. The print() is a template function that takes 2 arguments, i.e., a separator string (string sept) and the vector (constant vector<ele_type>& vector). Here ele_type represents the type of elements in the vector.
  2. This function contains a for loop which iterates over each vector element, printed to an output stream, followed by a comma (,) stored in a sept separator.
  3. The function then returns the output stream to the calling function.
  4. In the main function, a vector V is initialized with string elements and object cout is used to print the elements of vector V by calling the print() function.

Printing Vector In C++ Using Indices (Square Brackets/ Double Brackets & at() Function)

The simplest way to iterate through and print the vector elements is to use a simple for loop and access its elements using the at() function or index operator (denoted by []) with the corresponding index.

The at() function and the [] operator return the element present at the index mentioned inside the () and [] brackets, respectively. Given in the code snippet below is an example of how to print a vector in C++ using indices.

Code:

Output:

1.1 2.2 3.3 4.4 5.5

Explanation:

In the C++ program above,

  1. We begin by defining the template function print() that takes vector (const vector<ele_type>& vector) as an input argument. Here the ele_type represents the type of elements in the vector.
  2. The function uses a simple for loop, which iterates over each vector element using a [] operator where the integer variable, i, denotes the current position.
  3. Then in the main function, we initialize a vector V with float elements.
  4. Next, the vector object cout is used to print the elements of vector V with a space.

How To Print A Vector In C++ | 8 Methods Explained With Examples

How To Print A Vector In C++ Using std::copy?

The std::copy function is a function provided by the C++ Algorithm Library, which is used to copy a range of elements of a container from the present memory location to a new memory location. Or to a new container present at different memory locations. While printing a vector, it can be used to copy the vector contents to output stream cout using iterator ostream_iterator.

The code snippet below is an example of how to print a vector in C++ using the std::copy function:

Output:

U N S T O P

Explanation:

  1. The print() is a template function that takes a vector as input (const vector<ele_type>& vector) argument. And ele_type represents the type of elements in the vector.
  2. The function contains a copy algorithm that takes the V.begin() and V.end(), i.e., the beginning and the ending iterator, respectively, as input arguments.
  3. It also takes ostream_iterator<ele_type>(cout, " ")) as the third input argument where the “ “ is a space separator.
  4. The copy algorithm copies each vector element to ostream cout using the ostream_iterator.
  5. We then declare and initialize a vector V in the main function with the values U, N, S, T, O, P.
  6. The print function is then used to print the output on the console, and the program terminates with a return 0.

Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions

How To Print A Vector In C++ Using for_each() Function?

How to print a vector in C++ using for_each() function?

The use of the for_each() function also provides an elegant way to print the vector elements. It takes three input arguments, a start and end iterator, which defines or informs the function about the range of the vector that is to print. And then applies the function provided as the third input parameter to each element of the vector in the given range.

Let’s understand how to print a vector in C++ using the for-each() function with the help of an example given below.

Code:

Output:

A Vector Is Printed

Explanation:

  1. In this code, we use the for_each() function, present in the print_vector function, and it takes three input arguments, two iterators, and a function.
  2. The two iterators V.begin() and V.end(), act as the beginning and the ending iterator, respectively, which define the range of vector to be printed.
  3. The print function is the third input argument applied to each vector element.
  4. When the print function is called, it takes a vector element as the only input parameter and prints it followed by a space. This repeats for each element.
  5. In the main function, we declare and initialize the vector V, and then it is passed onto the print_vector function.

Printing C++ Vector Using The Lambda Function

A lambda function is a feature provided in modern C++ that is from C++ 11 onwards. These functions are the kind of separate functions that are or can be treated as any other class object or struct. In simple words, it can be used to just read the value of a vector variable or element without making any changes to it or accessing any other information related to it.

How to print a vector in C++ using lambda function?

We can use the lambda expression on each vector element to print the element without providing the element type. We will also take the help of the for_each() function as we have used in the above example.

Here is an example of how to print a vector in C++ using the Lambda function:

Output:

U N S T O P

Explanation:

In this code, we begin by declaring and initializing vector V with character elements. 

  1. We then use the lambda function that is defined in the square sequence containers [] and take const auto& element as an input argument.
  2. Here the keyword auto automatically interprets the element type of the vector and prints them with a space “ ” in between using the cout statement.
  3. The for_each algorithm is used for iteration over each vector element and takes V.begin() and V.end() as the beginning and the ending iterator, respectively.
  4. It also takes the lambda function as the third input argument.

How To Print Vector In C++ Using Iterators?

How to print a vector in C++ using iterators

Iterators are markers or pointers that point to the specific position of an element in a vector. Usually, we use constant iterators to get the start and end point of the vector, and another for loop iterates that iterates over each element in the defined range.

Here is an example of how to print an iterator of a vector in C++:

Output:

# U N S T O P P A B L E

Explanation:

  1. The print() is a template function that takes as input (const vector<ele_type>& vector) argument, where ele_type represents the type of elements in the vector.
  2. This function uses a for loop, which iterates over each vector element using the iterator, itr that points to the address of a vector element.
  3. The itr is dereferenced using the asterisk operator (*) and printed followed by a space, using cout.
  4. The constant iterators, cbegin() and cend(), define the starting and end points of the range of the vector to be printed.
  5. In the main function, we declare and initialize vector V with character elements. We then call the print() function to print the elements on the console. 

Conclusion

Vectors are similar to dynamic arrays but are automatically resizable. That is, since vector elements are stored in continuous memory locations, it is easy to iterate on them. Containers handle the storage. We have learned that there are multiple ways to print a vector in C++, including by overloading the left shift operator (<<), using range-based for-loop, comma separator, indices, copy() function, for_each() function, and more. 

Also read- 51 C++ Interview Questions For Freshers & Experienced (With Answers)

Frequently Asked Questions

Q. How to print vectors in C++ using an iterator?

Usually, we use constant iterators to get the start and end point of the vector, and another for loop iterates that iterates over each element in the defined range. An example code for the same is given below.

Code:

Output:

# U N S T O P

Explanation:

  1. The print() is a template function that takes vector (‘const vector<ele_type>& vector’) as an input argument and ele_type represents the type of elements in the vector.
  2. This function uses a for loop, which iterates over each vector element using the iterator itr.
  3. We deference the itr using the * operator and is printed followed by a space.
  4. The constant iterators cbegin() and cend() define the starting and end point of the range of the vector to be printed.

Q. How to print the first element of the vector in cpp?

The simplest way to print the first element of a vector in C++ is by using indices. Indexes refer to the position of the elements in a vector and are denoted by square brackets. Let's look at an implementation of the same for better understanding.

Code Example:

Output:

1.1

Explanation:

  1. The vector is first declared and initialized in the main function.
  2. V.begin() is a pointer that gives the address of the first element of the vector.
  3. The ‘*’ operator acts as a dereferencing operator that outputs the vector value present at the address pointed by V.begin() iterator.

Q. How is a vector created in C++?

When a vector is created in C++, the elements are inserted using the push_back() function. The elements are stored in adjacent memory locations, which allows easy traversal through the vector using iterators.

We use the following syntax to create a vector in C++:

vector <data_type> vector_name[vector_size];

Here,

  • vector is the keyword for creating them.
  • data_type refers to the type of elements in the vector.
  • vector_name refers to the name given to the vector being created.
  • vector_size is an optional field which refers to the number of elements in the vector.

Q. How to print a 2D string vector in C++?

We can use the nested for-loop to print a 2D vector of string type in C++. A nested loop is when we insert one for-loop inside another. Here the flow of control first passes through the outer loop and passes to the internal loop if the initial condition is met. The flow moves to the outer loop again when the inner loop terminates or finishes an iteration.

Let's take a look at the code snippet below to see how this is done:

Output:

Get Mentors
At Unstop
And Grow

Explanation:

We begin by declaring and initializing a vector in the main function with string elements. 

  1. The program then initiates a nested for loop, where the outer loop iterates over each row, and the inner loop is used to iterate over each column element of the current row indicated by variable ‘i’.
  2. We use str.size() to get the number of rows and str[0].size() to get the number of column elements in each row.
  3. The 2D string vector is printed using cout, with respective row elements in the same line and followed by space.

Q. Can you have a vector of multiple types in C++?

No. A vector of elements with different data types is not possible since the vector type is the property of a complete vector and is common to all of its elements. It is preferable to create a List in C++. It is a data structure that allows the storage of elements with different data types.

Q. How to print a char vector in C++?

There are multiple ways to print a vector in C++, for example, by overloading the left shift operator, using iterators, in-built functions, and indices, etc. Given below is an example of how to print a character array using indices.

Code:

Output:

C O D I N G

Explanation:

  1. The initialized character vector is printed using a simple for loop, which iterates over each vector element using an iterator itr.
  2. The auto keyword helps the itr to automatically get the data type of vector elements.

Q. Can we have a string vector in C++?

C++ gives you the ability to create a string vector by including a string library in the program. This enables programmers to initialize a vector with string elements. Let’s look at an example to gain a better understanding of the same.

Code:

Output:

This is a string vector.

Explanation:

  • We begin by including the string library to create a string vector. We also include other libraries important for creating vectors and printing the output on the console. 
  • Next, we initialize a string vector inside the main() function and initiate a for loop to iterate over its elements.
  • The simple for loop iterates over each vector element that is a string using an iterator, it. And prints the element using cout.
  • The auto keyword helps the itr to automatically get the data type of vector elements, and it is printed followed by a space.

This is how we can create a string vector. The example also showcases how to print a vector in C++ using a for-loop and space separator. 

You might also be interested in reading the following:

  1. References In C++ | Declare, Types, Properties & More (+Examples)
  2. Typedef In C++ | Syntax, Application & How To Use It (With Examples)
  3. Comment In C++ | Types, Usage, C-Style Comments & More (+Examples)
  4. Storage Classes In C++ & Its Types Explained (With Examples)
  5. History Of C++ | Detailed Explanation (With Timeline Infographic)
Edited by
Shivani Goyal
Manager, Content

I am an economics graduate using my qualifications and life skills to observe & absorb what life has to offer. A strong believer in 'Don't die before you are dead' philosophy, at Unstop I am producing content that resonates and enables you to be #Unstoppable. When I don't have to be presentable for the job, I'd be elbow deep in paint/ pencil residue, immersed in a good read or socializing in the flesh.

Tags:
Computer Science Engineering

Comments

Add comment
comment No comments added Add comment