c++打印包含结构的 vector

标签 c++ vector struct

我是一名 C++ 初学者。谁能告诉我如何打印名为 mailVector 的 vector 。这是我的代码:

#include<iostream>
#include<vector>
using namespace std;
struct eMailMsg {
string to; // i.e. "professor@stanford.edu"
string from; // i.e. "student@stanford.edu"
string message; // body of message
string subject; // i.e. "CS106 Rocks!"
int date; // date email was sent
int time; // time email was sent
};

int main(){
    vector <eMailMsg> mailVector;
    eMailMsg professor={"professor@stanford.edu","student@stanford.edu","body of message","CS106 Rocks",4,16};
    mailVector.push_back(professor);
    for( std::vector<eMailMsg>::const_iterator i = mailVector.begin(); i != mailVector.end(); ++i)
    std::cout << *i << ' ';

    return 0;
}

相应的错误是 Error 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const eMailMsg' (or there is no acceptable conversion)

更新ver1 :

#include<iostream>
#include<vector>
#include<iterator>
using namespace std;
struct eMailMsg {
string to; // i.e. "professor@stanford.edu"
string from; // i.e. "student@stanford.edu"
string message; // body of message
string subject; // i.e. "CS106 Rocks!"
int date; // date email was sent
int time; // time email was sent
};

ostream& operator<<(ostream& os, const eMailMsg& rightOp)
    {
   os << rightOp.to << " " << rightOp.from << "etc ...";//error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const std::string' (or there is no acceptable conversion)

   return os;
   // We're writing std::string here and C++ can do that
}

int main(){
    vector <eMailMsg> mailVector;
    eMailMsg professor={"professor@stanford.edu","student@stanford.edu","body of message","CS106 Rocks",4,16};
    mailVector.push_back(professor);

    for( std::vector<eMailMsg>::const_iterator i = mailVector.begin(); i != mailVector.end(); ++i)
std::cout << *i << ' ';

    return 0;
}

最佳答案

您正在尝试打印 eMailMsg类型。 C++ 不知道该怎么做,您需要告诉它。

重载 ostream& operator<<(ostream& os, const eMailMsg& rightOp)为了教它。

你可以这样做:

... {
   os << rightOp.to << " " << rightOp.from << "etc ...";
   return os;
   // We're writing std::string here and C++ can do that
}

关于c++打印包含结构的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20929724/

相关文章:

vector - 如何从 Racket 中的向量中获取最小整数

c - ‘sizeof’ 对不完整类型的无效应用

c - 如何更改C中结构体的数组成员

c++ - 错误: During startup program exited with code 0xc0000135

c++ - Cout vector 地址

c++ - 将 C++ vector 传递给方法导致未解析的外部

c - `typedef struct X { }` 和 `typedef struct { } X` 有什么区别?

c++ - 我如何在 C++ 中使用优先级队列?

c++ - 如何在给定两点的情况下沿直线移动物体?

c++ - 这个 static_cast 到底有什么不安全的地方?