简体   繁体   English

是否可以使用pair std:string和std :: vector重载&lt;&lt; operator for std :: map <int> ?

[英]Would it be possible to overload << operator for a std::map with pair std:string and std::vector<int>?

I previously overloaded the << operator for a std::map using template for a std::map<std::string, int> 我之前使用templatestd::map<std::string, int>重载了std::map<<运算符

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; 
} 

How can a template be written if the map , for instance, was std::map< std::string, std::vector<int> > ? 例如,如果mapstd::map< std::string, std::vector<int> > ,那么如何编写模板?

There are several options for. 有几种选择。

At first you could just provide a separate operator<< overload for std::vector , eg: 首先,您可以为std::vector提供单独的operator<< overload,例如:

template <typename T>
std::ostream& operator<< (std::ostream& s, std::vector<T> const& v)
{ /* your generic implementation */ return s; }

It will then be called for every vector in your map: 然后将为地图中的每个向量调用它:

os << it.first << " : " << it.second << "\n";
//                           ^ here...

I consider this the cleanest solution – but if it is too generic and you need something really different only for this specific map type, then you could either provide a separate overload for exclusively this type of map: 我认为这是最干净的解决方案 - 但如果它通用了,你只需要为这个特定的地图类型提供一些真正不同的东西,那么你可以为这种类型的地图提供一个单独的重载:

std::ostream& operator<<
        (std::ostream& s, std::map<std::string, std::vector<int>> const& m)
{ /* your specific implementation */ return s; }

or, alternatively, specialise your operator for it: 或者,专门为您的运营商服务:

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; }

Is it possible? 可能吗? Yes, you could write the code. 是的,你可以编写代码。

Is it allowed? 是允许的吗? No, it's undefined behavior to extend the std namespace with your own symbols unless explicitly specified. 不,除非明确指定,否则使用您自己的符号扩展std命名空间是未定义的行为。

Looking at your current approach, I wouldn't overload the existing method. 看看你目前的方法,我不会重载现有的方法。 I would provide a new method for the pair. 我会为这对提供一种新方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM