yaml-cpp到std::向量迭代的怪异行为
yaml-cpp to std::vector iteration weird behaviour
在读取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>>>>>
相关文章:
- 向后迭代 std::array 或 std::vector 的正确方法是什么?
- 在不使用vector.end()的情况下迭代std::vector
- 迭代 std::vector 时的分段错误
- 均匀迭代 std::vector<T> 和 std::vector<unique_ptr<T>>
- 在迭代 std::vector 时删除(间接)
- 为什么迭代 std::array 比迭代 std::vector 快得多?
- 使用正向迭代器反向迭代 std::vector
- 迭代 std::map 的更好方法
- 我可以在迭代 std::string 对象时删除它中的元素吗?
- std::算法友好的方式迭代'std::vector<std::vector<something>>
- 有没有一种安全的方法可以迭代 std::unique_ptr<int[]>?
- 使用 SWIG 在 PHP 中迭代 std::map
- 按排序顺序迭代 std::vector
- 以排序方式迭代 std::vector<std::p air<T,U> > 对象
- 插入后继续迭代std::map
- 迭代 std::set 会创建临时
- 在C++中迭代 std::set<std::string> 时出现分段错误
- 我如何迭代std::string来获得一组Freetype FT_ULong ?
- 在迭代std::列表时擦除
- 如何按照我自己的顺序/它们被插入的顺序迭代std::map值