我相信您的代码只需进行最少的更改即可按照您需要的方式运行。您所需要的只是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;
}