首页 > 解决方案 > 是否可以使用对 std:string 和 std::vector 为 std::map 重载 << 运算符?

问题描述

我之前重载了<<运算符 for a std::mapusing templatefor 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> >

标签: c++vectoroperator-overloadingstdmap

解决方案


有几种选择。

起初你可以只为 提供一个单独的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; }

推荐阅读