c++ - STL map 在删除第一对后不会添加一对

标签 c++ stl dictionary

在这段代码中,我在 map 上添加了一对,一切都很好,但是当我删除了不是最后一对时, map 不再添加任何对。我做错了什么??

SomeClass::add(Object object)
if (!object.empty())
{
    ObjectList::iterator result = find(object.name());
    if (result == ObjectList.end())
    {
        object.order(size() + 1);
        ObjectList.insert(orderedObject(object.order(), object));
    }
    else
    {
        ObjectList[result->first] = object;
    }
}

ObjectList 和 orderedObject 声明如下:

typedef std::pair<int, Object> orderedObject;
typedef std::map<int, Object> ObjectList;

这是删除代码:

SomeClass::eraseNamed(std::string aName)
{
    if (!isEmpty())
    {
        ObjectList::iterator result;
        result = find(aName);
        if (result != ObjectList.end())
        {
            ObjectList.erase(result);
            reorgObjectList();
            return true;
        }

    }
    return false;
}

对于查找方法:

ObjectList::iterator SomeClass::find(std::string aName)
{
    ObjectList::iterator result = ObjectList.begin();
    while (result != ObjectList.end())
    {
        if (aName == result->second.name())
            return result;
        result++;
    }
    return result;
}

对于 reorgObjectList:

bool SomeClass::reorgObjectList()
{
    ObjectList::iterator i=ObjectList.begin();
    int j=1;
    for (i = ObjectList.begin(); i != ObjectList.end(); ++i)
    {
        if(j!=i->second.order())
            i->second.order(j);
        j++;
    }
    return true;
}

有什么建议吗???

最佳答案

您输入的是 map 的大小,这似乎会导致您的问题。

所以如果你在 map 上有 3 个东西,你就会有

  1 => Obj1
  2 => Obj2
  3 => Obj3

如果你删除这些元素之一,比如 1,你将拥有

  2 => Obj2
  3 => Obj3

然后你再去insert,设置key为"size() + 1",size会返回2,你会尝试在key 2 + 1 == 3处插入,3已经被占用了。所以它要么被覆盖要么失败(不确定你的发现在上面是如何工作的)。

我不会以大小 + 1 插入,而是检查最后一个键并递增 1(如果这就是您想要管理键的方式)。

关于c++ - STL map 在删除第一对后不会添加一对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/860510/

相关文章:

arrays - swift:修改字典中的数组

java - 如何在java中将Map<String,TreeMap<String,String>> String转换为Json对象?

c++ - 共享内存中的 STL 结构

c++使用 vector 作为类私有(private)变量时构造函数的奇怪行为

c++ - 为什么 `equal` 在 C++ 中适用于 const char*?

C++ STL 集合用法

c# - 使用 LINQ 合并两个字典

c++ - C++ 的 Hello World 错误

c++ - C++ 中的未知错误消息 C2440

c++ - 列表迭代器在 STL 中不兼容的问题