是否可以为带有 std:string 和 std::vector 的 std::map 重载<<运算符<int>?
Would it be possible to overload << operator for a std::map with pair std:string and std::vector<int>?
我之前使用template
重载了std::map
的<<
运算符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::vector
提供一个单独的operator<<
重载,例如:
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
命名空间是未定义的行为。
看看你目前的方法,我不会重载现有方法。我会为这对夫妇提供一种新的方法。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;
- 为什么STD :: MAP需要操作员&lt;以及我如何写一个
- std::vector::reserve(未知m),我知道m<<;N(通常)并且知道N
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- C++运算符<<调用::ostream而不是std::osttream
- 是std :: set&lt; std :: future&gt;不可能存在
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- C++重载<<具有typedef'd std::vector
- 以x的倍数填充前导零,使用std::cout<<std::十六进制
- 错误:没有匹配'运算符<<"在'std::cout
- std::pair的默认构造函数<>将基本类型(int等)设置为零
- std::ostream&operator< & lt; (std:: ostream&压力,压力& &;val)
- 将std::endl传递给std::operator<<
- std::映射<>或std::vector<>在处理大型标志集时
- 重载& lt; & lt;使用命名空间std