我的C ++可能包含多个错误......第一个是如何在向量中添加struct元素
我的代码将是这样的:
#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;
mailVector[0]={"professor@stanford.edu","student@stanford.edu","body of message",4,16};
for( std::vector<eMailMsg>::const_iterator i = mailVector.begin(); i != mailVector.end(); ++i)
std::cout << *i << ' ';
system("pause");
return 0;
}
答案 0 :(得分:5)
您使用.push_back()
方法将某些内容放入向量中,因此对于初学者来说:
mailVector.pushBack(...)
代码:
eMailMsg myMailMsg = {"professor@stanford.edu","student@stanford.edu","body of message", 4, 16};
mailVector.pushBack(myMailMsg);
答案 1 :(得分:2)
要向向量添加元素,可以使用std::vector::push_back
:
mailVector.push_back({"professor@stanford.edu","student@stanford.edu","body of message",4,16});
大括号在传递给函数时构造一个新的eMailMsg
。 See a working code here.
您的语法用于使用新值替换元素(赋值)。
从C ++ 11开始,我们也有std::vector::emplace_back
,效率稍高。函数push_back
将现有对象复制或移动到向量中。但emplace_back
使用提供的构造函数参数“就地”构造它。它提供了构造函数参数:
mailVector.emplace_back("professor@stanford.edu","student@stanford.edu","body of message",4,16);
第三种方法(不推荐)是首先将向量调整为给定大小(std::vector::resize
,或最初在构造函数中),然后使用您在代码中使用的赋值语法。
您忘记了构建eMailMsg
对象的一个初始值设定项(参数):主题。
要使用eMailMsg
打印自定义类型的值(在您的情况下为std::cout
),您需要重载流操作符。典型的实现使用提供的流来打印多个内容,然后返回流以在一行中连接多个值:
std::ostream& operator<<(std::ostream &out, eMailMsg &mail) {
// Print only "to" and "from" for demonstration.
return out << "To: " << mail.to << "\nFrom: " << mail.from << "\n";
}