dev*_*bmw 6 c++ stl unordered-map reference c++11
使用值类型为引用C++ 11的unordered_map是否合法?
例如 std::unordered_map<std::string, MyClass&>
我已经设法使用VS2013进行编译但是我不确定它是否应该因为它导致一些奇怪的运行时错误.例如vector subscript out of range,在尝试erase元素时抛出.
一些谷歌搜索导致发现你不能有一个引用的向量,但我找不到任何有关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;
}
Run Code Online (Sandbox Code Playgroud)