【问题标题】:Read with boost::program_options and push_back onto std::vector?使用 boost::program_options 和 push_back 读取 std::vector?
【发布时间】:2011-02-15 17:32:30
【问题描述】:

我有一个包含端点条目列表的配置文件。每个条目都标有 [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 的新手,因此任何关于更好地阅读列表的方法的建议或任何其他帮助都将不胜感激。谢谢!

【问题讨论】:

    标签: c++ boost boost-program-options


    【解决方案1】:

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

    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 编号与向量中的正确索引相关联,除非在文件中保持严格的顺序。

    【讨论】:

    • 感谢您的回复!我仍然遇到问题...当我将po::value 替换为po::vector 时,我收到错误消息error: 'vector' is not a member of 'po'。 (我没有将它包含在 OP 中,但我使用的是namespace po = boost::program_options;)这可能是版本问题吗?我正在使用 Boost 1.40...
    • 不,不是版本问题;我的代码被破坏了。我已经纠正了。此外,我发现有趣的是 options_description 即使在 v. 1.41.1 中也不会将 std::string 作为第一个参数。
    • 代码现在可以编译,但我仍然遇到一些问题。使用您的typedef std::vector&lt; std::string &gt; vec_string;,当我声明空向量(vec_string mac;)代码段错误时。如果我为预期数量的端点 (vec_string mac(NUM_ENDPTS);) 分配空间,则只有向量中的第一个字符串会被写入,并且它会被每个后续配置文件条目覆盖。还有什么我需要添加到我的po::store(po::parse_config_file(...)) 命令的吗?
    • @tpm,您可以尝试在每个参数上设置multitoken()。但是,我不知道它是否会起作用,而且我无法通过阅读代码来判断。
    • 仍然没有骰子...我会继续戳它,再次感谢所有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 2013-10-15
    • 2021-06-18
    • 2023-03-21
    • 2015-01-15
    • 2023-01-11
    相关资源
    最近更新 更多