重载<< c ++ stl容器的运算符 [英] overloading << operator for c++ stl containers
问题描述
我希望我可以使用cout<< .对于stl设计器来说,实现起来似乎并不那么困难:假设<< T定义为T,<<因为容器可以只遍历元素并使用ofstream<<打印它们.
I wish I could just print contents of a set/vector/map by using cout << . It doesn't seem so difficult for the stl designers to implement : Assuming that << is defined for T, << for a container could just iterate through the elements and print them using ofstream << .
有没有一种我不知道的简单打印方法?
Is there an easy way to print them that I dont know of?
如果没有,是否有简单的解决方案?我读过一些地方,扩展stl类不是一个好主意.是这样,为什么?
If not, Is there an easy solution? I have read at places that extending stl classes is a bad idea. Is that so, and why?
如何定义类似重载打印功能的内容? 我正在寻找一个可以处理...的容器的递归函数 我同意不同的人会喜欢不同的格式,但是可以覆盖的东西总比没有好
how about defining an something like an overloaded print function? I am looking for a recursive function which can handle containers of containers of ... I agree that different people would like different formats, but something overridable is better than nothing
推荐答案
可能最简单的输出STL容器的方法是
Probably the easiest way to output an STL container is
std::copy(cont.begin(), cont.end(),
std::ostream_iterator<Type>(std::cout, " "));
其中Type
是cont
元素的类型(例如,如果cont
是std::vector<int>
类型,则Type
必须是int
).
where Type
is the type of the elements of cont
(e.g. if cont
is of type std::vector<int>
then Type
must be int
).
当然,您可以使用任何ostream代替std::cout
.
Of course instead of std::cout
you can use any ostream.
这篇关于重载<< c ++ stl容器的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!