c++ - 通过map key检查最后插入的项目是否存在

标签 c++ dictionary stl iterator

#include <map>

struct X {
    int x;

    bool operator < (const X v) const
    {
        return (x < v.x);
    }
};

struct Y {
    int y;
};

int main()
{
    X x = {1};
    Y y = {2};

    std::map <X, Y> Z;
    std::pair<std::map<X, Y>::iterator,bool> lastval;

    // Insert a value
    lastval = Z.insert(std::pair<X, Y>(x, y));

    // Erase the "last" inserted item
    Z.erase(lastval.first->first);

    // Error: Check if last item was erased or if iterator is valid
    if (lastval.first != Z.end())
    {
        /* ... */
    }
}

我在检查最后插入的项目是否已删除时收到错误。有什么办法可以检查吗?

最佳答案

使用 map::erase 的返回值

if(Z.erase(lastval.first->first))
{
    /* item has been erased */
}

// Erase the "last" inserted item
Z.erase(lastval.first->first);

if(Z.find(x) == Z.end())
{
    /* item has been erased */
}

您还应该更改您的 operator<

bool operator < (const X& v) const
//                      ^
//           take arg by reference to avoid unnecessary copying

关于c++ - 通过map key检查最后插入的项目是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21298362/

相关文章:

c++ - std::enable_if 使用其内部类型而不使用它

python - 字典的平均值

c++ - 基于非成员函数的参数进行调度

c++ - 使用 libpam0g-dev 和 cmake 构建应用程序

c# - 如何将元组用作字典 C# 中的键

python - 对象与字典 : how to organise a data tree?

c++ - STL ref 和 cref 函数

c++ - 理解GDB中STL多重集的红黑树遍历

c++ - 在 STL 中使用 memcpy

c++ - 理解OpenGL红皮书中的一段代码