简体   繁体   English

为什么const_iterator可以与std :: map :: erase一起使用

[英]Why const_iterator could be used with std::map::erase

I was under the impression one cant use erase on a const iterator . 我觉得一个人不能在const iterator上使用erase Check this code . 检查此代码
Why does the below code compile (C++11, gcc)? 为什么以下代码编译(C ++ 11,gcc)?

long getMax(const bool get_new)
{
    long max_val=0;

    TO now=getNow();

    map<TO, long>& m=get_new?m_new:m_old;

    for(auto it=m.cbegin(); it !=m.cend())
    {
        if(now.compareTime((*it).first)<lookback)
        {
            max_val=max(max_val,
                        (*it).second);
            ++it;
        }
        else
        {
            it=m.erase(it);
        }
    }

    return max_val;
}

The map itself is not constant, but my understanding is that the const iterator should make this fail. 地图本身并不是常数,但我的理解是const iterator应该使它失败。

The behavior has changed from C++11; 行为已从C ++ 11改变; std::map::erase takes const_iterator as its parameter. std :: map :: eraseconst_iterator作为参数。

void erase( iterator pos );           // (until C++11)
iterator erase( const_iterator pos ); // (since C++11)
iterator erase( iterator pos );       // (since C++17)

For std::map::erase , the passed iterator is just used as the position where the element would be deleted, not for modifying the element through it. 对于std::map::erase ,传递的迭代器仅用作删除元素的位置,而不是用于通过它修改元素。 That means const_iterator would be fine. 这意味着const_iterator会很好。 Before C++11, the support for const_iterator was not very good, but the situation has changed from C++11. 在C ++ 11之前,对const_iterator的支持不是很好,但是情况已经从C ++ 11改变了。 You should use const_iterator instead of iterator when possible now. 现在可以使用const_iterator而不是iterator

Positions are independent of the constness of their access. 职位独立于其访问的常数。 It was (is?) quite common that functions doing a search return const_iterator because they actually do not change the container at all. 执行搜索的函数返回const_iterator是很常见的,因为它们实际上根本不会更改容器。 However, it is desirable to use the obtained position for mutations of the sequences, eg, to insert() an element at the corresponding position or to erase() the located element. 然而,期望将所获得的位置用于序列的突变,例如,在相应位置insert()元素或者erase()所定位的元素。 As a result, the container where extended to support use of const_iterator with mutating operations. 结果,扩展的容器支持使用const_iterator进行变异操作。

It seems the relevant paper is N2350 . 相关论文似乎是N2350 I'm not sure if this paper is the latest version. 我不确定这篇论文是否是最新版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM