boostorg / boostorg/json

Support for ordered insert/erase on json::object

Ouverte
#748 1 commentaire 0 réactions 0 personnes assignées Voir sur GitHub
Langage dominant
C++
Étoiles
479
Forks
110
Merge moyen
10 j 3 h
PR mergées (30 j)
5

Description

I have a json that needs to be manipulated and maintaining the order of the keys in the object is really imported (even though it is supposed to be unordered key-value map).

Currently insertions are ordered so creating a json::object and inserting at the end will preserve the order. A work around I have now is something like this:
```c++
template
void ordered_insert_before(boost::json::object& o, K&& key, P&& p)
{
auto x = boost::json::object(o.storage());
x.reserve(o.size() + 1);
bool added = false;
for (auto&& [k, v] : o)
{
if (k == key && !added)
{
x.insert(std::forward

(p));
added = true;
}
x.insert(boost::json::object::value_type{std::move(k), std::move(v)});
}
if (!added)
{
x.insert(std::forward

(p));
}
o.swap(x);
}

template
void ordered_erase(boost::json::object& o, K&& key)
{
auto x = boost::json::object(o.storage());
x.reserve(o.size());
for (auto&& [k, v] : o)
{
if (k != key)
{
x.insert(boost::json::object::value_type{std::move(k), std::move(v)});
}
}
o.swap(x);
}
```

There are of course O(N). Is there interest for adding these as member functions or free functions with stronger ordering guarantees but worse O(N) complexity + allocations?

Guide de contribution

Ouvrir le guide de contribution

Évaluation

Cette issue n'a pas encore été évaluée.

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.