繁体   English   中英

unordered_map,引用为值

[英]unordered_map with reference as value

使用值类型为引用C ++ 11的unordered_map是否合法?

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

我已经设法使用VS2013进行编译但是我不确定它是否应该因为它导致一些奇怪的运行时错误。 例如vector subscript out of range当尝试erase元素时,抛出vector subscript out of range

一些谷歌搜索导致发现你不能有一个引用的向量,但我找不到任何有关unordered_map的内容。

更新

进一步的实验表明, vector subscript out of range与引用的unordered_map无关,因为它是我的代码中的一个错误。

mapunordered_map对引用很好,这里有一个工作示例

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM