c++ - 在字符串数组中动态创建和存储数据
问题描述
我正在使用 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;
}
推荐阅读
- bigcommerce - Bigcommerce 模具产品网格或卡片
- visual-studio-code - 在不使用鼠标的情况下在 VSCode 编辑器中运行 python 代码时如何交换焦点?
- firebase - 从 Firebase 数据库中读取数据
- javascript - 使用javascript单击按钮时如何在ul中显示多个div的p标签的内容
- c++ - generic_category 和 system_category 之间有什么区别?
- kotlin - 在 Kotlin 中,是否通过标准库支持栈、队列、堆、树等数据结构?
- c# - 在没有输入[@type='file']元素的硒中上传文件
- python - 如何在没有递归的情况下构建线段树?
- shebang - 从今天起如何将多个参数传递给shebang
- python - 在 django 中创建新帖子时自动发送电子邮件