gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:33 27 4
gpt4 key购买 nike

#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++ - 通过映射键检查最后插入的项目是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21298362/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com