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

时间:2010-11-21 17:44:12

标签: c++ reference map

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

示例声明:

map<int, SomeStruct&> map_num_to_struct;

使用示例:

...
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;
...

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

6 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:3)

不,不是。但是,您可以使用指针作为值类型。

答案 2 :(得分:2)

我不这么认为,如果我没记错的话,引用应该被视为对某个元素的常量指针。但你可以使用指针来达到同样的效果。

答案 3 :(得分:2)

不,你不能使用引用,但你可以使用指针。你似乎在你的例子中混淆了两者。尝试:

map<int, SomeStruct *> map_num_to_struct;
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;

答案 4 :(得分:1)

值类型必须是可分配的,而引用则不是。

无论如何,您可以使用tr1 reference_wrapper

答案 5 :(得分:0)

我相信有可能,但有限制。由于无法在以后分配参考,因此您将无法在地图上调用 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;
}

我不知道新的C ++标准是否可以实现这一点,但是至少可以在GCC和clang上使用。