首页 > 解决方案 > 在字符串数组中动态创建和存储数据

问题描述

我正在使用 libconfig c++ 库来获取存储的数据,并且需要在不知道将通过配置文件传递的变量数量的情况下将该数据存储在 c++ 中的字符串数组中。我知道这在 c++ 中实际上是不可能的,但我正在努力寻找最佳实践来做到这一点,而其他解决方案似乎对我正在做的事情没有实际意义。下面是我尝试获取字符串文件类型并将所有结果单独存储在字符串数组中的代码部分。

    try {
    for (int i = 0; i < cfg.getRoot()["files"].getLength(); ++i) {
        // Only output the record if all of the expected fields are present.
        string filetype;
        if (!(cfg.getRoot()["files"][i].lookupValue("filetype", filetype)))
            continue;

        cout << filetype << endl;
    }
}
catch (const SettingNotFoundException &nfex) {
    // Ignore.
}

为您现在可能面临的面部问题道歉,我是一名仍在学习绳索的大学生,并且目前在我的个人项目上工作得很好。

标签: c++arraysstringlibconfig

解决方案


我相信您的代码只需进行最少的更改即可按照您需要的方式运行。您所需要的只是std::vector<std::string>包含您从循环中记录的所有字段:

std::vector<std::string> filetypes;

try {
    for (int i = 0; i < cfg.getRoot()["files"].getLength(); ++i) {
        // Only output the record if all of the expected fields are present.
        std::string filetype;
        if (!(cfg.getRoot()["files"][i].lookupValue("filetype", filetype)))
            continue;

        //The use of std::move is optional, it only helps improve performance.
        //Code will be logically correct if you omit it.
        filetypes.emplace_back(std::move(filetype));
    }
}
catch (const SettingNotFoundException &nfex) {
    // Ignore.
}

//Proof that all values have been properly stored.
for(std::string const& filetype : filetypes) {
    std::cout << filetype << std::endl;
}

我不知道返回类型cfg.getRoot()["files"]是什么,但存储该对象以提高代码的可读性可能是值得的:

std::vector<std::string> filetypes;

try {
    //One of these is correct for your code; I don't know which.
    //auto & files = cfg.getRoot()["files"];
    //auto const& files = cfg.getRoot()["files"];
    //I'm assuming this is correct
    auto files = cfg.getRoot()["files"];

    for (auto const& entry : files) {
        // Only output the record if all of the expected fields are present.
        std::string filetype;
        if (!(entry.lookupValue("filetype", filetype)))
            continue;

        //The use of std::move is optional, it only helps improve performance.
        //Code will be logically correct if you omit it.
        filetypes.emplace_back(std::move(filetype));
    }
}
catch (const SettingNotFoundException &nfex) {
    // Ignore.
}

//Proof that all values have been properly stored.
for(std::string const& filetype : filetypes) {
    std::cout << filetype << std::endl;
}

推荐阅读