我知道,来自 JsonCPP 的 ValueIterator
不能直接用于标准 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)
);
最佳答案
有一个派生自 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));
关于c++ - 将 JsonCPP ValueIterator 与 STL 算法结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18724009/