我是一名 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/