如何使用 C++ 在磁盘上保存自定义类型元素的向量、读取它并再次将其解析为向量

How to save a vector of a custom type of elements on disk, read it, and parse it into a vector again using C++

矢量类型为TrackInfo:

class TrackInfo
{
public:
    TrackInfo(URL& _url, String& _title, double& _length, String _fileFormat);

    URL url;
    String title;
    double length;
    String fileFormat;
};


====================================================================================

std::vector<TrackInfo> tracks;
TrackInfo track(fileURL, fileName, length, fileFormat);
tracks.push_back(track);
tracks.push_back(track);

那么,如何将这个矢量图保存在电脑上,然后在需要时重新读取它,并再次将文件转换成相同的矢量图?

我使用了 nlohmann JSON。你可以在这里找到它 -> https://json.nlohmann.me/

我的代码:

std::vector<TrackInfo> StoreData::jsonToTrackInfo(json jsonFile)
{
    std::vector<TrackInfo> tracks;

    for (json jsonf : jsonFile["Playlist"])
    {
        // Try to parse the data. If there is an error, return the empty vector.
        // If one of the Playlist tracks has a problem, it won't be parsed and will parse the rest of the playlist.
        try
        {
            String urlString = jsonf["url"];
            String title     = jsonf["title"];
            double length    = jsonf["length"];
            String format    = jsonf["format"];
            URL url { urlString };

            TrackInfo track(url, title, length, format);
            tracks.push_back(track);
        }
        catch (const std::exception&)
        {
            //..
        }
    }
    return tracks;
}

json StoreData::trackInfoToJson(std::vector<TrackInfo> tracks)
{
    json j;

    // Convert each track into JSON data.
    for (TrackInfo track : tracks)
    {
        j.push_back(
            {
                {"url"  , track.url.toString(false).toStdString()},
                {"title" , track.title.toStdString() },
                {"length", track.length},
                {"format", track.fileFormat.toStdString()}
            }
        );
    }

    json jsonFile;
    jsonFile["Playlist"] = j;   

    return jsonFile; // return the Json File
}

JSON 文件的输出应如下所示:

{
    "Playlist": [
        {
            "format": ".mp3",
            "length": 106.0,
            "title": "c_major_theme.mp3",
            "url": "file:///C%3A/Users/me/Desktop/tracks/c_major_theme.mp3"
        },
        {
            "format": ".mp3",
            "length": 84.0,
            "title": "fast_melody_regular_drums.mp3",
            "url": "file:///C%3A/Users/me/Desktop/tracks/fast_melody_regular_drums.mp3"
        }
    ]
}

您可以在他们的网站上找到有用的示例:https://json.nlohmann.me/api/basic_json/#non-member-functions

我希望这个答案对您有所帮助 :D