如何使用std :: copy来打印用户定义的类型 [英] How to use std::copy for printing a user defined type
问题描述
下面的代码非常适合打印std::string
Below is the code that works perfectly for print the values of type std::string
std::vector<std::string> v;
v.push_back("this");
v.push_back("is");
v.push_back("a");
v.push_back("test");
std::copy(v.begin(),v.end(),std::ostream_iterator<std::string>(std::cout,","));
但是当我尝试打印用户定义的类型(结构)时,代码无法编译:
But when I am trying to print a user defined type (a structure), code is not compiling:
struct Rec
{
int name;
int number;
int result;
};
int main()
{
Rec rec1 = {1,1,1};
Rec rec2 = {2,1,1};
Rec rec3 = {3,1,1};
Rec rec4 = {4,1,1};
Rec rec5 = {4,1,1};
std::vector<Rec> v;
record.push_back(rec1);
record.push_back(rec2);
record.push_back(rec3);
record.push_back(rec4);
record.push_back(rec5);
std::copy(v.begin(),v.end(),std::ostream_iterator<Rec>(std::cout,","));
return 1;
}
我在这里想念什么?
推荐答案
std::ostream_iterator
是写的单遍OutputIterator 类型T的连续对象进入std::basic_ostream
对象,用于 它是使用operator<<
构造的.可选的分隔符字符串 每次写操作后,都会将其写入输出流.写 迭代器(是否已取消引用)时执行操作 被分配给.std::ostream_iterator
递增是空操作.
std::ostream_iterator
is a single-pass OutputIterator that writes successive objects of type T into thestd::basic_ostream
object for which it was constructed, usingoperator<<
. Optional delimiter string is written to the output stream after every write operation. The write operation is performed when the iterator (whether dereferenced or not) is assigned to. Incrementing thestd::ostream_iterator
is a no-op.
(经评论确认)
对于自定义记录,您不会超载operator <<
.使用以下代码使运算符重载.
You are not overloading operator <<
for the custom record. Use the following code to overload the operator.
ostream& operator<<(ostream& os, const Rec& r)
{
os << r.name << '-' << r.number << '-' << r.result;
return os;
}
这篇关于如何使用std :: copy来打印用户定义的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!