c++命令行选项器的使用
参考文献:https://blog.csdn.net/morning_color/article/details/50241987
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
namespace bpo = boost::program_options;
int main(int argc, char const *argv[])
{
//步骤一: 构造选项描述器和选项存储器
//选项描述器,其参数为该描述器的名字
bpo::options_description opts("Display all options");
//选项存储器,继承自map容器
bpo::variables_map vm;
//步骤二: 为选项描述器增加选项
//其参数依次为: key, value的类型,该选项的描述
opts.add_options()
("version,v","Show version info.")
("help,h", "Show this help doc.")
("start_idx,s", bpo::value<int>(), "Start index")
("end_idx,e", bpo::value<int>(), "End index")
("visiualize",bpo::value<bool>(),"Is visiualize or not.");
bpo::store(bpo::parse_command_line(argc, argv, opts), vm);
//assert(vm.count("config") && vm.count("visualize") && vm.count("start") && vm.count("end"));
//步骤四: 参数解析完毕,处理实际信息
//count()检测该选项是否被输入
if(vm.count("help") ){//若参数中有help选项
//options_description对象支持流输出, 会自动打印所有的选项信息
std::cout << opts << std::endl;
}
if(vm.count("version") ){
//variables_map(选项存储器)是std::map的派生类,可以像关联容器一样使用,
//通过operator[]来取出其中的元素.但其内部的元素类型value_type是boost::any,
//用来存储不确定类型的参数值,必须通过模板成员函数as<type>()做类型转换后,
//才能获取其具体值.
std::cout << "version is 0.1." << std::endl;
}
if(vm.count("start_idx")){
std::cout << "start index is:"<<vm["start_idx"].as<int>()<<std::endl;
}
if(vm.count("end_idx")){
std::cout << "End index is:"<<vm["end_idx"].as<int>()<<std::endl;
}
return 0;
}
CMakelists.txt
cmake_minimum_required(VERSION 2.8)
find_package(
Boost
COMPONENTS program_options
REQUIRED)
add_executable(randomly_stacked_box_data main.cpp)
target_link_libraries(
randomly_stacked_box_data
${Boost_LIBRARIES}
)
message(${Boost_LIBRARIES})
message(${Boost_LIBRARIES})
Display all options:
-v [ --version ] Show version info.
-h [ --help ] Show this help doc.
-s [ --start_idx ] arg Start index
-e [ --end_idx ] arg End index
--visiualize arg Is visiualize or not.