1

我有一个包含端点条目列表的配置文件。每个条目都标有 [endpt/n] 标题(用于第 n 个端点),并由 MAC 和 IP 地址组成。我想使用 boost::program_options 将地址读取为字符串,并将结果 push_back 到两个向量上。我已经查看了 program_options 文档,但我无法找到我正在寻找的内容......这是一个端点条目的示例:

[endpt/2]
mac=ff-22-b6-33-91-3E
ip=133.22.32.222

这是我目前用来将每个端点的 MAC 和 IP 选项添加到 boost::options_description 的代码:

std::vector<std::string> mac(NUM_ENDPTS);
std::vector<std::string>  ip(NUM_ENDPTS);

for(int e = 0; e < NUM_ENDPTS; e++)
{
    //convert endpoint 'e' to a string representing endpoint heading
    std::stringstream tmp;   tmp.clear();   tmp.str("");   tmp << e;
    std::string strEndpt = tmp.str();
    std::string heading = "endpt/"+strEndpt;

    cfig_file_options.add_options()
        ((heading+".mac").c_str(), po::value<std::string>(&mac[e]), ("ENDPT MAC")
        ((heading+".ip").c_str(),  po::value<std::string>( &ip[e]), ("ENDPT IP")
    ;
}

po::variables_map vm;
po::store(po::parse_config_file(config_stream, cfig_file_options), vm);
po::notify(vm);

此代码工作正常,但出于几个原因,我想为 MAC 和 IP 地址声明空向量,并在 boost 读取它们时将选项 push_back 到它们上。我是 Boost 的新手,因此任何关于更好地阅读列表的方法的建议或任何其他帮助都将不胜感激。谢谢!

4

1 回答 1

1

完全按照您的意愿进行操作很简单。首先,使用po::value< vector< std::string > >而不是po::value< std::string >作为程序选项提供了对向量的特殊支持。然后,将您的两个向量直接引用为

typedef std::vector< std::string > vec_string;

cfig_file_options.add_options()
  ((heading+".mac").c_str(), po::value< vec_string >(&mac), "ENDPT MAC")
  ((heading+".ip").c_str(),  po::value< vec_string >( &ip), "ENDPT IP")
;

这里的关键是所有的mac和ip地址都使用公共向量进行存储。我应该指出,这不一定将 ini 文件中的 endpt 编号与向量中的正确索引相关联,除非在文件中保持严格的顺序。

于 2011-03-02T11:09:24.857 回答