打印自定义类矢量图 [英] print custom class vector
本文介绍了打印自定义类矢量图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一些地方,我需要打印出一个自定义类的向量.我目前遍历向量,并在每个元素上调用写入函数,即
In several places, I need to print out a vector of a custom class. I currently loop through the vector and call my write function on each element, that is
vector < customClass > ::迭代器 元素 = 元素 .begin(); |
while(element!= elements.end()){{ |
> } |
ofstream fileOut("FILE.TXT"); |
vector<customClass>:: iterator element = elements.begin(); |
while(element != elements.end()) { |
element->write(fileOut); |
element++; |
} |
推荐答案
这是一个函数模板,您可以调用任何类型为const成员函数的类型的向量,这些函数名为write take一个std :: ostream& ::
Here's a function template that you can call for vectors of any type that has a const member function named write taking an std::ostream&:
void ́write_vec(std :: vector< T> const & vec,std :: ostream& os) |
(类型名称std :: vector< T> :: const_iterator iter = vec.begin(),iter_end = vec.end(); iter!= iter_end; ++ iter) |
} |
template<typename T> |
void write_vec(std::vector<T> const& vec, std::ostream& os) |
{ |
for (typename std::vector<T>::const_iterator iter = vec.begin(), iter_end = vec.end(); iter != iter_end; ++iter) |
iter->write(os); |
} |
这篇关于打印自定义类矢量图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文