C++:是否可以使用引用作为地图中的值?

Jon*_*han 14 c++ reference map

是否可以在C++中使用引用作为标准映射容器中的值?
如果没有 - 为什么不呢?

示例声明:

map<int, SomeStruct&> map_num_to_struct;
Run Code Online (Sandbox Code Playgroud)

用法示例:

...
SomeStruct* some_struct = new SomeStruct();
map_num_to_struct[3] = *some_struct;
map_num_to_struct[3].some_field = 14.3;
cout<<some_struct.some_field;
...
Run Code Online (Sandbox Code Playgroud)

我希望看到14.3印刷......

sbi*_*sbi 13

不需要.STL容器值类型需要可分配.引用不可分配.(您不能为它们分配不同的对象以供参考.)

  • 从什么时候开始需要对容器值类型进行赋值?它们需要可复制。参考确实不是“可复制的”,但您的答案在技术上是错误的。我错过了什么? (2认同)

Stu*_*etz 5

不,这不对。不过,您可以使用指针作为值类型。


ben*_*eno 5

我相信这是可能的,但有限制。由于引用在稍后阶段不可分配,因此您将无法在地图上调用operator[] 。但是,您可以调用各种其他成员函数。只要你不违反任何参考规则。例如:

// You need the instances to exist before
auto a1 = SomeStruct();
auto a2 = SomeStruct();
auto a3 = SomeStruct();

// Creating the map with an initializer list.
std::map<int, SomeStruct&> map_num_to_struct = {
    { 1, a1 },
    { 2, a2 },
    { 5, a3 }
};

// The following won't work because operator[] returns
// a reference to the value, which can't be re-assigned.
// map_num_to_struct[6] = a1;

// These will work.
map_num_to_struct.insert({6, a1});
map_num_to_struct.insert(std::pair<int, SomeStruct&>(7, a1));

// Iterating through the map.
for (auto &a: map_num_to_struct) {
    cout << a.first << ": " << a.second.some_field << endl;
}

// We can't use operator[] for indexing.
// map_num_to_struct[5].do_something();
auto a_iter = map_num_to_struct.find(5);
if (a_iter != map_num_to_struct.end()) {
    cout << a_iter->first << ": " << a_iter->second.some_field << endl;
    a_iter->second.some_field = 14.3;
    cout << a_iter->first << ": " << a_iter->second.some_field << endl;
}
Run Code Online (Sandbox Code Playgroud)

我不知道较新的 C++ 标准是否使这成为可能,但它至少适用于 GCC 和 clang。