打印容器和枚举

  • 参考代码
#include <iostream>
#include <map>
#include <vector>
#include <sstream>

using namespace std;

/*
 * 打印map
 */
template<typename _Key, typename _Value>
std::ostream &operator<<(std::ostream &stream, const std::map<_Key, _Value> &mpObj)
{
    size_t i = 0;
    stream << "----> map.size=" << mpObj.size() << endl;
    stream << "{" << endl;
    for (const auto &item : mpObj) {
        stream << "[" << i++ << "]    key=" << item.first << ", value=" << item.second << endl;
    }
    stream << "}" << endl;
    return stream;
}

/*
 * 打印vector
 */
template<typename _Value>
std::ostream &operator<<(std::ostream &stream, const std::vector<_Value> &vecObj)
{
    size_t i = 0;
    stream << "----> vector.size=" << vecObj.size() << std::endl;
    stream << "{" << std::endl;
    
    for (const auto &item : vecObj) {
        stream << "[" << i++ << "]    value=" << item << std::endl;
    }
    
    stream << "}" << std::endl;
    return stream;
}


enum Color
{
    color_red, 
    color_blue, 
    color_green
};

#ifndef PRINT_ENUM
#define PRINT_ENUM(enumKey) (int)enumKey<<"("<<#enumKey<<")"
#endif
/*
 * 打印枚举
 */
std::ostream &operator<<(std::ostream &stream, const Color &obj)
{
    switch (obj) {
        case color_red:
            stream << PRINT_ENUM(color_red);
            break;
        
        case color_blue:
            stream << PRINT_ENUM(color_blue);
            break;
        
        case color_green:
            stream << PRINT_ENUM(color_green);
            break;
        
        default:
            stream << "error!!!(not enum Color)";
            break;
    }
    return stream;
}


int main()
{
    map<int, string> mp;
    mp[1] = "a";
    mp[2] = "b";
    mp[3] = "c";
    
    cout << "mp = " << mp << endl;
    Color color = color_green;
    cout << "color " << color << endl;
    
    return 0;
}
  • 输出结果
mp = ----> map.size=3
{
[0]    key=1, value=a
[1]    key=2, value=b
[2]    key=3, value=c
}

color 2(color_green)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值