yaml-cpp到std::向量迭代的怪异行为

yaml-cpp to std::vector iteration weird behaviour

本文关键字:迭代 std 向量 yaml-cpp      更新时间:2023-10-16

在读取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

两者之间有什么区别?为什么我必须明确声明向量?即使在.begin()之前的语句周围加括号也没有什么区别。像这样:

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

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

由于我是YAML的新手,我对阅读这样一个文件的任何改进建议都很满意,但这不是我主要关心的问题。

您的YAML无效!例如,参见在线解析器;并且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>>>>>