【问题标题】:Check if last item inserted exists through map key通过映射键检查插入的最后一项是否存在
【发布时间】:2014-01-23 02:48:39
【问题描述】:
#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())
    {
        /* ... */
    }
}

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

【问题讨论】:

    标签: c++ map stl iterator


    【解决方案1】:

    使用来自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&lt; 更改为

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

    【讨论】:

      猜你喜欢
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      • 2010-10-12
      • 2016-03-19
      相关资源
      最近更新 更多