[英]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无关,因为它是我的代码中的一个错误。
map
和unordered_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.