How To Print A Vector In C++ | 8 Methods Explained With Examples
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.
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.
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:
- 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.
- This function contains a for loop which iterates over each vector element, printed to the output stream, followed by a space.
- The function then returns the output stream to the calling function.
- 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:
- 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.
- In the main function, we declare a vector of integers named myVector and initialize it with five elements, 1, 2, 3, 4, and 5.
- We use std::cout to print the message Vector elements: on the console. This text will be displayed before the vector elements.
- Next, the program starts with the range-based for-loop.
- 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.
- 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.
- 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.
- 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:
- 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.
- 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.
- The function then returns the output stream to the calling function.
- 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,
- 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.
- 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.
- Then in the main function, we initialize a vector V with float elements.
- Next, the vector object cout is used to print the elements of vector V with a space.
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:
- 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.
- 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.
- It also takes ostream_iterator<ele_type>(cout, " ")) as the third input argument where the “ “ is a space separator.
- The copy algorithm copies each vector element to ostream cout using the ostream_iterator.
- We then declare and initialize a vector V in the main function with the values U, N, S, T, O, P.
- 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?
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:
- 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.
- 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.
- The print function is the third input argument applied to each vector element.
- 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.
- 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.
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.
- We then use the lambda function that is defined in the square sequence containers [] and take const auto& element as an input argument.
- Here the keyword auto automatically interprets the element type of the vector and prints them with a space “ ” in between using the cout statement.
- 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.
- It also takes the lambda function as the third input argument.
How To Print 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:
- 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.
- 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.
- The itr is dereferenced using the asterisk operator (*) and printed followed by a space, using cout.
- The constant iterators, cbegin() and cend(), define the starting and end points of the range of the vector to be printed.
- 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:
- 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.
- This function uses a for loop, which iterates over each vector element using the iterator itr.
- We deference the itr using the * operator and is printed followed by a space.
- 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:
- The vector is first declared and initialized in the main function.
- V.begin() is a pointer that gives the address of the first element of the vector.
- 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.
- 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’.
- We use str.size() to get the number of rows and str[0].size() to get the number of column elements in each row.
- 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:
- The initialized character vector is printed using a simple for loop, which iterates over each vector element using an iterator itr.
- 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:
- References In C++ | Declare, Types, Properties & More (+Examples)
- Typedef In C++ | Syntax, Application & How To Use It (With Examples)
- Comment In C++ | Types, Usage, C-Style Comments & More (+Examples)
- Storage Classes In C++ & Its Types Explained (With Examples)
- History Of C++ | Detailed Explanation (With Timeline Infographic)
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Comments
Add comment