Question

I know, ValueIterator from JsonCPP cannot be used in standard STL algorithms directly. But is there a some "indirect" way to use it in STL algorithms (maybe via Boost.Iterator or something like this)? I want something likes to following:

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)
  );
Was it helpful?

Solution

There is a custom iterator derived from 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;
};

And client code is following:

std::copy(JsonIter(root.begin()), JsonIter(root.end()), std::back_inserter(vec));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top