如何使用std :: copy打印用户定义的类型

时间:2017-02-08 06:58:25

标签: c++ c++11 iterator

以下代码适用于打印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,","));

但是当我尝试打印用户定义的类型(结构)时,代码没有编译:

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;
}

我在这里缺少什么?

3 个答案:

答案 0 :(得分:6)

您需要为记录实现流插入运算符,如下所示:

#include <iostream>
#include <iterator>
#include <vector>

struct Rec
{
    int name;
    int number;
    int result;
};

std::ostream& operator<<(std::ostream& os, const Rec& rec)
{
    os << "{name: " << rec.name << ", number: " << rec.number 
       << ", result: " << rec.result << "}";
    return os;
}

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;
    v.push_back(rec1);
    v.push_back(rec2);
    v.push_back(rec3);
    v.push_back(rec4);
    v.push_back(rec5);

    std::copy(v.begin(), v.end(), std::ostream_iterator<Rec>(std::cout, ",\n"));

    return 1;
}

答案 1 :(得分:5)

来自std::ostream_iterator

  

std::ostream_iterator是一个写入的单通道OutputIterator   将类型为T的连续对象放入std::basic_ostream对象中   它是使用operator<<构建的。可选的分隔符字符串   每次写操作后写入输出流。写   迭代器(无论是否取消引用)执行操作   分配给。增加std::ostream_iterator是无操作。

(通过评论确认)

您没有为自定义记录超载operator <<。使用以下代码重载运算符。

ostream& operator<<(ostream& os, const Rec& r)  
{  
    os << r.name << '-' << r.number << '-' << r.result;  
    return os;  
}

答案 2 :(得分:0)

正如Mohit所提到的,你必须超载&lt;&lt;对于您的自定义结构,因为只有您知道结构中的内容,因此您负责打印它

struct Rec
{
 int name;
 int number;
 int result;
 friend ostream& operator<<(ostream& os, const Rec& rec); // Here is the overloaded << operator 
};
ostream& operator<<(ostream& os, const Rec& rec)
{
   os<<"[" << rec.name<< '/' << rec.number<< '/' << rec.result<<"] \n";
}
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> record;
    record.push_back(rec1);
    record.push_back(rec2);
    record.push_back(rec3);
    record.push_back(rec4);
    record.push_back(rec5);
    std::copy(record.begin(),record.end(),std::ostream_iterator<Rec>(std::cout,""));  // Now no problem here
    return 1;
}