1

我知道,ValueIteratorJsonCPP 不能直接用于标准 STL 算法。但是是否有一些“间接”的方式在 STL 算法中使用它(可能通过Boost.Iterator或类似的东西)?我想要以下内容:

Json::Value root = getJson(); //came from outside
std::vector<Json::Value> vec;

std::copy
  ( make_some_smart_iterator(...) // some iterator produced with start of root
  , make_some_smart_iterator(...) // some iterator produced with end of root
  , std::back_inserter(vec)
  );
4

1 回答 1

1

有一个自定义迭代器派生自boost::iterator_facade.

#include <boost/iterator/iterator_facade.hpp>

class JsonIter : public boost::iterator_facade
     <JsonIter, Json::ValueIterator, boost::forward_traversal_tag, Json::Value &>
{
public:
    JsonIter() {}
    explicit JsonIter(Json::ValueIterator iter) : m_iter(iter) {}
private:
    friend class boost::iterator_core_access;

    void increment() { ++m_iter; }
    bool equal(const JsonIter &other) const {return this->m_iter == other.m_iter;}
    Json::Value &dereference() const { return *m_iter; }
    Json::ValueIterator m_iter;
};

客户端代码如下:

std::copy(JsonIter(root.begin()), JsonIter(root.end()), std::back_inserter(vec));
于 2013-09-11T13:19:31.590 回答