修改最后插入到std :: map

Modifying last insertion to std::map

本文关键字:map std 最后 插入 修改      更新时间:2023-10-16

在下面的示例中,我尝试将元素插入 std::map并将迭代器插入最后一个插入的元素,但是我无法修改它。

#include <map>
struct X {
    int 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 = Z.insert(std::pair<X, Y>(x, y));
    // Error: Expression must be a modifiable lvalue;
    lastval.first->first.x = 0;
}

我该怎么做?

std::map中的密钥(std::set的元素)是不可变的 - 您无法更改它们,因为这可能会更改订购并破坏地图。std:map<K, V>类型的值实际上是std::pair<const K, V>。因此,就您而言,lastval.first->second可以更改,但是lastval.first->first是只读的,因为它是const

相关文章: