Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I want to achieve an upgraded function. #1566

Closed
3038922 opened this issue Apr 14, 2019 · 1 comment
Closed

I want to achieve an upgraded function. #1566

3038922 opened this issue Apr 14, 2019 · 1 comment

Comments

@3038922
Copy link

3038922 commented Apr 14, 2019

I want to achieve an upgraded function.
According to the target key, add and delete obj. without changing value.
It's OK to add obj in this way. But once erase, it's wrong.
if i ues json::diff(), if the target value is different, he will update the value. I don't want him to update the value.

image

void SysBase::upDateJson(json &source, const json &target)
{
    if (source.type() == target.type())
        switch (source.type())
        {
            case json::value_t::object:
            {
                //第一遍:遍历机器人文件的的元素
                for (auto it = source.begin(); it != source.end(); ++it)
                {
                    if (target.find(it.key()) != target.end())
                    {
                        //递归调用以比较对象的对象值
                        upDateJson(it.value(), target[it.key()]);
                    }
                    else
                    {
                        //找到一个不在o中的键 ->删除它
                        source.erase(it);
                        logger->debug({"删除: ", it.key()});
                    }
                }
                //第二遍:遍历用户数据里的元素
                for (auto it = target.begin(); it != target.cend(); ++it)
                {
                    if (source.find(it.key()) == source.end()) //如果机器人文件没找到和目标文件里同名的元素
                    {
                        //添加他
                        source[it.key()] = it.value();
                        logger->debug({"添加: ", it.key()});
                    }
                }
                break;
            }
            default:
                break;
        }
    return;
}
@jaredgrubb
Copy link
Contributor

You are modifying the container during iteration; changing the contianer and expecting that the iterators stay valid is tricky and you have to be very careful doing that. In particular, you should consider using the return value of "it = source.erase(it)" instead of expecting that "++it" is still a valid operation.

@3038922 3038922 closed this as completed Apr 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants