在字符串数组中动态创建和存储数据

Dynamically creating and storing data in a string array

本文关键字:存储 数据 创建 动态 字符串 数组      更新时间:2023-10-16

我正在使用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.
}

对于您现在可能遇到的脸掌,我是一名仍在学习绳索的大学生,并且目前正在进行个人项目,并且正在

提前完成我的课程。

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