是否可以用 std:string 和 std::vector<int> 对 std::map 重载 << 运算符?
Would it be possible to overload << operator for a std::map with pair std:string and std::vector<int>?
我之前为 std::map
重载了 <<
运算符,使用 template
为 std::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> >
,如何编写模板?
可能吗?是的,你可以写代码。
允许吗?不,除非明确指定,否则使用您自己的符号扩展 std
命名空间是未定义的行为。
看你目前的做法,我不会重载现有的方法。我会为这对提供一个新的方法。
有几个选项。
起初您可以为 std::vector
提供单独的 operator<<
重载,例如。 g.:
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; }
我之前为 std::map
重载了 <<
运算符,使用 template
为 std::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> >
,如何编写模板?
可能吗?是的,你可以写代码。
允许吗?不,除非明确指定,否则使用您自己的符号扩展 std
命名空间是未定义的行为。
看你目前的做法,我不会重载现有的方法。我会为这对提供一个新的方法。
有几个选项。
起初您可以为 std::vector
提供单独的 operator<<
重载,例如。 g.:
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; }