在struct构建的向量中添加元素

Ben*_*gie -2 c++ struct vector

我的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;
}
Run Code Online (Sandbox Code Playgroud)

Iva*_*čić 5

你用.push_back()方法把东西放在矢量中,所以对于初学者:

mailVector.pushBack(...)
Run Code Online (Sandbox Code Playgroud)

码:

eMailMsg myMailMsg = {"professor@stanford.edu","student@stanford.edu","body of message", 4, 16};
mailVector.pushBack(myMailMsg);
Run Code Online (Sandbox Code Playgroud)