In this article, we will discuss how to print a vector using std::cout in C++.
By default we can directly pass a vector object to the cout
in C++. As, ‘cout’ calls the operator<<()
function of each passed object. So, we can overload a operator<<
function of vector like this,
#include <iostream> #include <vector> /* Overload the << operator to print a vector object */ template <typename T> std::ostream& operator<<( std::ostream& outputStream, const std::vector<T>& vectorObj) { // Print all the elements of vector using loop for (auto elem : vectorObj) { outputStream<< elem << " "; } return outputStream; }
It is a template function, that accepts any kind of vector, and uses a for loop to print the vector contents. Once this function is defined, then we can directly pass a vector object to console. Like this,
// create a vector, and initialize with 10 integers std::vector<int> vectorObj {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; // display vector on console std::cout << vectorObj << std::endl;
It will print the contents of vector like this,
11 12 13 14 15 16 17 18 19 20
This technique will work for any type of vector object. We can use this to print a vector strings with std::cout. Like this,
std::vector<std::string> vecOfStrs {"Hi", "this", "is", "from", "a", "vector"}; // display vector on console std::cout << vecOfStrs << std::endl;
It will print the contents of vector like this,
Hi this is from a vector
This way we can print all elements of a vector by directly using the std::cout. Let’s see a complete example, where we will print all the contents of vector by just passing it to cout.
Frequently Asked:
- C++: Convert Array to Vector (7 Ways)
- How to use vector efficiently in C++?
- Convert a String to a Vector of Bytes in C++
- Check if two vectors are equal in C++
#include <iostream> #include <vector> /* Overload the << operator to print a vector object */ template <typename T> std::ostream& operator<<( std::ostream& outputStream, const std::vector<T>& vectorObj) { // Print all the elements of vector using loop for (auto elem : vectorObj) { outputStream<< elem << " "; } return outputStream; } int main () { // create a vector, and initialize with 10 integers std::vector<int> vectorObj {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; // display vector on console std::cout << vectorObj << std::endl; std::vector<std::string> vecOfStrs {"Hi", "this", "is", "from", "a", "vector"}; // display vector on console std::cout << vecOfStrs << std::endl; return 0; }
Output:
11 12 13 14 15 16 17 18 19 20 Hi this is from a vector
So, today we learned how to print a vector using std::cout in C++. Thanks.