c++ - yaml-cpp 到 std::vector 迭代奇怪的行为

标签 c++ vector stdmap yaml-cpp

我在读取 yaml 文件时发现了一些(在我看来)相当奇怪的东西。也许你们中的一位可以向我解释这两种代码之间的区别。

我尝试读取的 yaml 文件看起来像这样:

map:
  - [0 0 0 0]
    - 0:
      - 0.123
    - 1:
      - -0.234
  - [0 0 0 1]
    - 0:
      - 0.00
    - 1:
      - 1.234
# and many more vector to int to doubles.

现在我正在尝试将其读入 std::map<std::vector<int>, std::map<int, double> >以备后用。

我尝试使用来自 yaml-cpp 的 STL 转换来做到这一点:

std::map<std::vector<int>, std::map<int, double> > the_map = node.as<std::map<std::vector<int>, std::map<int, double> > >();

但由于这不起作用(现在没有错误消息,但这并不是真正的问题,只是作为解释)我写了我自己的读取例程,如下所示:

YAML::Node node = YAML::LoadFile(name);
for(YAML::const_iterator n = node["map"].begin(); n != node["map"].end(); ++n){
    auto n_0 = (*n).begin();
    for(auto it = n_0->first.as<std::vector<int> >().begin(); it != n_0->first.as<std::vector<int> >().end(); ++it){
        std::cout << *it << " ";
    }
    // Some more stuff
}

它会导致一些奇怪的输出:

937068720 21864 0 0 
937068720 21864 0 1 

但是如果我把它改成这段代码:

YAML::Node node = YAML::LoadFile(name);
for(YAML::const_iterator n = node["map"].begin(); n != node["map"].end(); ++n){
    auto n_0 = (*n).begin();
    std::vector<int> vec = n_0->first.as<std::vector<int> >();
    for(auto it = vec.begin(); it != vec.end(); ++it){
        std::cout << *it << " ";
    }
    // Some more stuff
}

一切如预期:

0 0 0 0
0 0 0 1

两者有什么区别?为什么我必须特别声明 vector ? 甚至在 .begin() 之前的语句两边加上括号没有区别。像这样:

for(auto it = (n_0->first.as<std::vector<int> >()).begin(); it != (n_0->first.as<std::vector<int> >()).end(); ++it)

有人能给我解释一下吗?第一个和第二个代码有什么区别?

由于我是 YAML 的新手,我很高兴收到任何关于阅读此类文件的改进建议,但这不是我主要关心的问题。

最佳答案

您的 YAML 无效!参见,例如 online parser ;并且 yaml-cpp 同意:使用 YAML 运行实用函数 util/parse 会得到:

yaml-cpp: error at line 3, column 5: end of sequence not found

也许你的意思是这样的:

map:
  [0 0 0 0]:
    - 0:
      - 0.123
    - 1:
      - -0.234
  [0 0 0 1]:
    - 0:
      - 0.00
    - 1:
      - 1.234

这至少是有效的 YAML,但它可能不是您期望的格式。分析如下:

map:           // map of string ->
  [0 0 0 0]:   //  map of vector of int ->
    - 0:       //   vector of map of int to ->
      - 0.123  //    vector of double
    - 1:
      - -0.234
  [0 0 0 1]:
    - 0:
      - 0.00
    - 1:
      - 1.234

在标准库函数中,这将是一个

std::map<string, std::map<std::vector<int>, std::vector<std::map<int, std::vector<double>>>>>

关于c++ - yaml-cpp 到 std::vector 迭代奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58649394/

相关文章:

c++ - Lambda 作为输出迭代器

c++ - 在 XP 上找不到序号 ComCtl32.dll C++

c++ - 连接传感器后,Arduino 驱动的伺服电机停止工作

c++ - vector 中的 vector 在第二维生成重复值

c++ - 使用单词键将多个行号的 vector 添加到我的 map

C++:从 std::map 继承

c++ - Valgrind - 无效的读写

c++ - 在容器中查找派生对象

c++ - std :map check whether two objects are equal?如何

c++ - 节点句柄与 std::unique_ptr