c++ - 是否可以使用对 std:string 和 std::vector 为 std::map 重载 << 运算符?
问题描述
我之前重载了<<
运算符 for a std::map
using template
for astd::map<std::string, int>
template <typename T, typename S>
std::ostream & operator<<(std::ostream & os, const std::map<T, S>& v)
{
for (auto it : v)
os << it.first << " : " << it.second << "\n";
return os;
}
map
例如,如果是 ,如何编写模板std::map< std::string, std::vector<int> >
?
解决方案
有几种选择。
起初你可以只为 提供一个单独的operator<<
重载std::vector
,例如:
template <typename T>
std::ostream& operator<< (std::ostream& s, std::vector<T> const& v)
{ /* your generic implementation */ return s; }
然后将为地图中的每个向量调用它:
os << it.first << " : " << it.second << "\n";
// ^ here...
我认为这是最干净的解决方案——但如果它过于通用,并且您只需要针对这种特定地图类型真正不同的东西,那么您可以专门为这种类型的地图提供单独的重载:
std::ostream& operator<<
(std::ostream& s, std::map<std::string, std::vector<int>> const& m)
{ /* your specific implementation */ return s; }
或者,专门针对它的操作员:
template <>
std::ostream& operator<< <std::string, std::vector<int>>
(std::ostream& s, std::map<std::string, std::vector<int>> const& m)
{ /* your specific implementation */ return s; }
推荐阅读
- video - FFMPEG 如何使用循环、缩放、叠加位置向 mp4 视频添加 gif 水印
- javascript - JS:拒绝可以排除在承诺之外吗?
- webrtc - 如何将原始数据从网络音频流式传输到 webrtc 数据通道
- ios - 如何从 Realm 中的 2 个表中获取数据
- android - 如何使用 Firebase 仅使用电话号码和 otp 实现现有用户登录
- c++ - 元组的可变参数模板被反转
- ssl - 使用 .crt 文件和 ca 签名证书生成 .jks 文件
- java - 如何将图片从imageview发送到gmail?
- laravel - 在 AWS Serverless 平台上部署 Laravel (laravel-mix) 应用程序
- python - 获取用户输入时,我想检查两个值,但是,我使用的代码不断循环