操作符重载在 C++ 中打印矢量、映射、对的内容...
在本文档中,我们将讨论一个程序,了解 C++ 中的操作符重载,以打印矢量、映射和对中的内容。
操作符重载就是操作符的功能,能让它们对用户定义的对象进行操作,并以类似的方式进行处理。
示例
矢量
#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;
}输出
[4, 2, 17, 11, 15]
映射
#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;
}输出
a : 2 b : 3 d : 5
对
#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;
}输出
(45, 7)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP