C++:提升program_options:多个参数列表
C++: Boost program_options: Multiple lists of arguments
我目前正在与boost::program_options
合作。我的程序应该将任意数量的任意长度的"列表"作为参数(除其他外)。例如,用户应该能够调用
./myprogram -list item1 item2 item3 -list item1 item2 -list item1 item2
显然,我不想得到一个列表/向量,结果是所有项目一个接一个,而是(在这种情况下)三个列表/向量(或者,例如,一个包含元素的向量),每个列表有两个或三个项目(每个项目都应该是一个字符串,但我想这无关紧要)。正如我之前所说,列表的数量(以及每个列表的项目数量!)应该是任意的。我怎样才能用boost::program_options
做到这一点?
这可以在没有大量额外代码的情况下完成。秘诀是将解析步骤与存储步骤分开,就像本答案中所做的那样。
解析器将返回一个键/值结构容器,因为选项来自用户。如果多次提交选项,则容器将为每个选项提交提供一个单独的条目。扫描特定选项并按照我们想要的方式组织其值非常简单。
下面是一个示例,该示例在单独的行上打印出每个输入多标记选项:
#include <iostream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int argc, char *argv[]) {
// Define a multi-token option.
po::options_description desc("Allowed options");
desc.add_options()
("list", po::value<std::vector<std::string>>()->multitoken(), "multiple values");
// Just parse the options without storing them in a map.
po::parsed_options parsed_options = po::command_line_parser(argc, argv)
.options(desc)
.run();
// Build list of multi-valued option instances. We iterate through
// each command-line option, whether it is repeated or not. We
// accumulate the values for our multi-valued option in a
// container.
std::vector<std::vector<std::string>> lists;
for (const po::option& o : parsed_options.options) {
if (o.string_key == "list")
lists.push_back(o.value);
}
// If we had other normal options, we would store them in a map
// here. In this demo program it isn't really necessary because
// we are only interested in our special multi-valued option.
po::variables_map vm;
po::store(parsed_options, vm);
// Print out the multi-valued option, each separate instance on its
// own line.
for (size_t i = 0; i < lists.size(); ++i) {
for (size_t j = 0; j < lists[i].size(); ++j)
std::cout << lists[i][j] << ' ';
std::cout << 'n';
}
return 0;
}
下面是一个示例调用(在 coliru 直播):
$ ./po --list 1 2 3 --list foo bar --list how now brown cow
1 2 3
foo bar
how now brown cow
相关文章:
- 概念中的cv限定符需要表达式参数列表
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- 错误 没有与参数列表匹配的重载函数"getline"实例
- std::vector 没有重载函数的实例与参数列表匹配
- 模板参数列表中的 false 在模板初始化期间计算为什么?
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- 构造函数/函数声明参数列表中的统一初始化
- 模板化检查是否存在带有参数列表的类成员函数?
- 如何将类成员方法的参数列表自动填充写入可变参数?
- 带有整数的变量参数列表
- 转发变量参数列表以模拟 std::thread
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- C++-将具有引用的长参数列表重构为结构
- 缺少别名模板C++参数列表
- C++如果两个模板函数都与参数列表匹配,将调用哪个模板
- "extern"声明以及带有和不带参数列表的类模板实例的后续定义
- 使用显式模板参数列表和 [temp.arg.explicit]/3 的函数调用的演绎失败
- 没有函数模板的实例与我不知道为什么的参数列表匹配
- 我可以使用宏自动构建参数列表吗?
- 类成员函数参数列表是否可以依赖于模板参数?