通过映射键检查是否存在最后插入的项目

时间:2014-01-23 02:48:40

标签: 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};

    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())
    {
        /* ... */
    }
}

检查最后插入的项目是否已被删除时出错。有没有办法检查它?

1 个答案:

答案 0 :(得分:2)

使用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