C++ 通过映射键检查最后插入的项目是否存在 #包括 结构X{ int x; 布尔运算符

C++ 通过映射键检查最后插入的项目是否存在 #包括 结构X{ int x; 布尔运算符,c++,map,stl,iterator,C++,Map,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};

检查最后插入的项目是否已擦除时出错。有什么方法可以检查它吗?

使用

您还应该更改
运算符
#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())
    {
        /* ... */
    }
}
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 */
}
bool operator < (const X& v) const
//                      ^
//           take arg by reference to avoid unnecessary copying