
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Operator overloading in C++ to print contents of vector, map, pair ..
In this tutorial, we will be discussing a program to understand operator overloading in C++ to print contents of vector, map and pair.
Operator overloading is the function of operators which gives them the ability to act on User defined objects and work accordingly in a similar fashion.
Example
Vector
#include <iostream> #include <vector> using namespace std; template <typename T> ostream& operator<<(ostream& os, const vector<T>& v){ os << "["; for (int i = 0; i < v.size(); ++i) { os << v[i]; if (i != v.size() - 1) os << ", "; } os << "]\n"; return os; } int main() { vector<int> vec{ 4, 2, 17, 11, 15 }; cout << vec; return 0; }
Output
[4, 2, 17, 11, 15]
Map
#include <iostream> #include <map> using namespace std; template <typename T, typename S> ostream& operator<<(ostream& os, const map<T, S>& v){ for (auto it : v) os << it.first << " : " << it.second << "\n"; return os; } int main(){ map<char, int> mp; mp['b'] = 3; mp['d'] = 5; mp['a'] = 2; cout << mp; }
Output
a : 2 b : 3 d : 5
Pair
#include <iostream> using namespace std; template <typename T, typename S> ostream& operator<<(ostream& os, const pair<T, S>& v){ os << "("; os << v.first << ", " << v.second << ")"; return os; } int main(){ pair<int, int> pi{ 45, 7 }; cout << pi; return 0; }
Output
(45, 7)
- Related Articles
- How to print out the contents of a vector in C++?
- Overloading unary operator in C++?
- How to implement operator overloading in C#?
- How to use Operator Overloading in C#?
- Traversing contents of a hash map in Java
- Overloading array index operator [] in C++
- Rules for operator overloading in C++
- Java program to convert the contents of a Map to list
- Print contents of a file in C
- Increment ++ and Decrement -- Operator Overloading in C++
- map operator= in C++ STL
- What is overloading a unary operator in C++?
- C++ Program to Subtract Complex Number using Operator Overloading
- map::operator[] in C++ STL Program
- How will you explain Python Operator Overloading?

Advertisements