C++ JsonCPP - Removing objectValue from an arrayValue

三世轮回 提交于 2019-12-03 03:06:15
tommygr

I finally had some time to dig into the source code and the easy answer is - No.

An arrayValue object is really just an ObjectValue defined as an std::map. If you call std::map::erase() on an object in the map you will interrupt the consecutive sequence index_ Key for the array. Sdt::Maps don’t allow you to edit the Key in the map so you would have to move all the Value object pointers in the map up one and delete the last entry before end() to actually "delete" the object.

That sounds like a lot of overhead. Why do I have to move everything up? ...you may ask. Because the JsonCPP Writer Classes use the map[] index to print out the values. If it doesn't find the key ( because of a gap in the series) it returns nullValue for that index. That’s what you see when you call root.toStyledString() to convert back to a string. After a while you have these "null," all over the place. From a Value object, if you’re not calling the const version ( const Value &operator[]( ArrayIndex index ) const; )you will insert the nullValue object into the Array. The parser uses the Value::operator[]( ArrayIndex index ) version to insert new dafaultValue objects into the map while its tokenizing your JSON.

Answer: No. You can’t delete an object from an arrayValue without making code changes to clean up the map.

More info here: Changing the key of an element inside a std::map

There is now removeIndex(), but as tommygr says, it is an expensive operation in the current implementation.

Json::Value new_items;
int c = 0;
for(int i = 0; i < items.size(); i++)
{
    if(items[i] != selected_item)
    {
        new_items[c] = items[i];
        c++;
    }
}
items = new_items;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!