gpt4 book ai didi

c++ 映射删除函数不能与迭代器一起正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:47 25 4
gpt4 key购买 nike

我正在通过以下方式使用删除从 map 中删除元素,但它无法正常工作。为什么?它并没有删除所有内容。

float nw_cut=80.0;
for(it=nw_tot1.begin();it!=nw_tot1.end();it++)
{
float f=(float) ((float) it->second/lines)*100.0;
if ( f < nw_cut )
{
nw_tot1.erase(it);
}
}

最佳答案

来自 std::map::erase() :

References and iterators to the erased elements are invalidated. Other references and iterators are not affected.

如果 erase(it) 被调用,则 it 无效,然后被 for 循环使用,导致未定义的行为。存储 erase() 的返回值,它返回一个指向被删除元素之后的下一个元素的迭代器(自 c++11 起),并且仅在 erase() 时递增没有被调用:

for(it = nw_tot1.begin(); it != nw_tot1.end();)
{
float f=(float) ((float) it->second/lines)*100.0;

if ( f < nw_cut ) it = nw_tot1.erase(it);
else ++it;
}

在 c++03(以及 c++11)中,这可以通过以下方式完成:

for(it = nw_tot1.begin(); it != nw_tot1.end();)
{
float f=(float) ((float) it->second/lines)*100.0;

if ( f < nw_cut ) nw_tot1.erase(it++);
else ++it;
}

关于c++ 映射删除函数不能与迭代器一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17295661/

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