分配给地图迭代器会导致值更改而不是引用
Assigning to a map iterator causes value change without being a reference
我不明白为什么在 std::map 中分配给迭代器->second 会将值修改到映射中
#include <typeinfo>
#include <map>
#include <iostream>
int main() {
std::map<int, int> lol;
lol[2] = 33;
auto it = lol.find(2);
it->second = 91; // This changes the map's value
std::cout << typeid(it->second).name(); // This just shows 'int', not a reference
std::cout << lol[2]; // 91
return 0;
}
难道 it->second
只是一个 int 而不是引用吗?
isn't it->second
just an int and not a reference?
是的,它只是一个 int
。 *it
给你一个std::pair<int const, int>&
,一个对map
中节点实际值的引用。但成员访问 second
实际上只是一个 int
。 trait "is a reference" 和 trait "is assignable to" 是不等价的——你可以赋值给非引用,有些引用你不能赋值。 it->second
给你一个类型为 int
的 lvalue,你可以通过它来赋值,就像:
int i = 4;
i = 5; // i is not a reference, but you can assign it here
就是说,typeid()
无论如何都不会为您提供引用类型,因为引用和 cv 资格已从类型分析中删除。另见 .
那说的,你大概想看的是decltype((it->second))
(是的,双倍的括号,双倍的乐趣)。这实际上给了你 int&
,因为该表达式是 int
.
类型的左值
我不明白为什么在 std::map 中分配给迭代器->second 会将值修改到映射中
#include <typeinfo>
#include <map>
#include <iostream>
int main() {
std::map<int, int> lol;
lol[2] = 33;
auto it = lol.find(2);
it->second = 91; // This changes the map's value
std::cout << typeid(it->second).name(); // This just shows 'int', not a reference
std::cout << lol[2]; // 91
return 0;
}
难道 it->second
只是一个 int 而不是引用吗?
isn't
it->second
just an int and not a reference?
是的,它只是一个 int
。 *it
给你一个std::pair<int const, int>&
,一个对map
中节点实际值的引用。但成员访问 second
实际上只是一个 int
。 trait "is a reference" 和 trait "is assignable to" 是不等价的——你可以赋值给非引用,有些引用你不能赋值。 it->second
给你一个类型为 int
的 lvalue,你可以通过它来赋值,就像:
int i = 4;
i = 5; // i is not a reference, but you can assign it here
就是说,typeid()
无论如何都不会为您提供引用类型,因为引用和 cv 资格已从类型分析中删除。另见
那说的,你大概想看的是decltype((it->second))
(是的,双倍的括号,双倍的乐趣)。这实际上给了你 int&
,因为该表达式是 int
.