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

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

我在这里错过了什么?

最佳答案

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

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

关于c++ - 如何使用 std::copy 打印用户定义的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42106614/

相关文章:

c++ - 如何运行 .h 中的函数列表

c++ - 请有人解释为什么这里含糊不清?

python - 在 Python 中按排序顺序从排序的迭代器中产生?

python - 在索引看起来像数字的内容时,Python 中的 "three dots"是什么意思?

c++ - 如何在模板类的内部类中编写虚函数?

c++ - (C++) 2^32=0 但 2^31 * 2 有效

c++ - 当 chrome 是默认浏览器时,ShellExecute 无法在 Windows 8 上打开页面

c++ - 如何将等待条件变量的 "stop"分离线程?

c++ - 尽管编译了库的通用版本和 i386 版本,但未找到体系结构 i386 的符号

c++ - 数据成员是否形成范围?