本文介绍了如何使用std :: copy来打印用户定义的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码非常适合打印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;
}
我在这里想念什么?
推荐答案
(经评论确认)
对于自定义记录,您不会超载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来打印用户定义的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!