如何将结构推回向量

How to pushback a struct into a vector

本文关键字:向量 结构      更新时间:2023-10-16
using namespace std;
struct Movie {
    string title;
    string director;
    string genre;
    string yearRelease;
    string duration;
};
int main(){
    cout << "Hi";
    ifstream fin;
    string line;
    vector <Movie> m;
    fin.open("Movie_entries.txt");
    while (getline(fin, line)) {
        cout << line << endl;
        stringstream lineStream(line);
        getline(lineStream, m.title, ',');
        getline(lineStream, m.director, ',');
        getline(lineStream, m.genre, ',');
        getline(lineStream, m.yearRelease, ',');
        getline(lineStream, m.duration, ',');
        m.push_back({title, director, genre, yearRelease, duration});
    }
}

我正在尝试将结构推回矢量以存储我的数据,并且在如何准确执行此操作时遇到了麻烦。这就是我目前拥有的。

你只需要创建一个结构变量;为它设置属性;然后将该结构推送到向量。

在C++中,声明一个结构变量,Movie aMovie;就足够了。无需struct Movie aMovie;.

using namespace std;
    struct Movie {
        string title;
        string director;
        string genre;
        string yearRelease;
        string duration;
    };
int main(){
    cout << "Hi";
    ifstream fin;
    string line;
    vector <Movie> m;
    fin.open("Movie_entries.txt");
    while (getline(fin, line)) {
        cout << line << endl;
        stringstream lineStream(line);
        struct Movie aMovie;
        getline(lineStream, aMovie.title, ',');
        getline(lineStream, aMovie.director, ',');
        getline(lineStream, aMovie.genre, ',');
        getline(lineStream, aMovie.yearRelease, ',');
        getline(lineStream, aMovie.duration, ',');
        m.push_back(aMovie);
    }
}