以值作为参考的unordered_map [英] unordered_map with reference as value

查看:87
本文介绍了以值作为参考的unordered_map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有类型为引用C ++ 11的unordered_map是否合法?

Is it legal to have an unordered_map with the value type being a reference C++11?

例如 std :: unordered_map< std :: string,MyClass&>

我设法将其与VS2013一起编译,但是我不确定是否应该会导致一些奇怪的运行时错误。例如,当试图擦除一个元素时,会抛出矢量下标超出范围

I have managed to get this to compile with VS2013 however I'm not sure whether it's supposed to as it is causing some strange runtime errors. For example vector subscript out of range is thrown when trying to erase an element.

一些谷歌搜索导致发现您无法获得参考向量,但我找不到关于unordered_map的任何信息。

Some googling resulted in finding out that you can't have a vector of references but I can't find anything about an unordered_map.

进一步的实验表明,向量下标超出范围与引用的unordered_map无关,因为

Further experimentation has shown that the vector subscript out of range was not related to the unordered_map of references as it was a bug in my code.

推荐答案

map unordered_map 可以引用,这里是一个有效的示例

map and unordered_map are fine with references, here a working example :

#include <iostream>
#include <unordered_map>

using UMap = std::unordered_map<int,int&>;

int main() {
    int a{1}, b{2}, c{3};
    UMap foo { {1,a},{2,b},{3,c} };

    // insertion and deletion are fine
    foo.insert( { 4, b } );
    foo.emplace( 5, d );
    foo.erase( 4 );
    foo.erase( 5 );

    // display b, use find as operator[] need DefaultConstructible
    std::cout << foo.find(2)->second << std::endl;

    // update b and show that the map really map on it
    b = 42;
    std::cout << foo.find(2)->second << std::endl;

    // copy is fine
    UMap bar = foo; // default construct of bar then operator= is fine too
    std::cout << bar.find(2)->second << std::endl;
}

这篇关于以值作为参考的unordered_map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆