直接迭代所有元素是不可能的;文档说 http://www.boost.org/doc/libs/1_52_0/doc/html/boost_propertytree/container.html
没有办法迭代整个树。
现在,您可以使用递归,并在每个级别应用 STL 算法来模仿它;它不符合您在下面的示例中在单个循环中执行此操作的要求,但它确实有效:
template <typename InputIt, typename OutputIt, typename Compare>
void collect(InputIt first, InputIt last, OutputIt dest, Compare comp)
{
typedef typename std::iterator_traits<InputIt>::reference reference;
std::copy_if (
first, last, dest,
[comp] (reference what) { return comp(what.first); });
std::for_each (
first, last,
[dest, comp] (reference what) { collect(what.second.begin(), what.second.end(), dest, comp); });
}
std::vector<std::pair<std::string, ptree>> match;
collect(
xml.begin (), xml.end (), std::back_inserter(match),
[] (const std::string& key) { return key == "ElementIWant"; });
for (auto pair: match)
{
std::cout << pair.first << std::endl;
}
这是一个“完全”递归并保留出现顺序的版本:
template <typename InputIt, typename OutputIt, typename Compare>
void collect_recursive(InputIt first, InputIt last, OutputIt dest, Compare comp)
{
typedef typename std::iterator_traits<InputIt>::reference reference;
if (first == last)
{
return;
}
auto begin = first->second.begin ();
auto end = first->second.end ();
if (begin != end)
{
collect_recursive (begin, end, dest, comp);
}
if (comp (first->first))
{
dest = *first;
}
collect_recursive (++first, last, dest, comp);
}