gpt4 book ai didi

c++ - 以引用为值的 unordered_map

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:10 24 4
gpt4 key购买 nike

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

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

我已经设法让它与 VS2013 一起编译,但是我不确定它是否应该这样做,因为它会导致一些奇怪的运行时错误。例如vector subscript out of range尝试 erase 时抛出一个元素。

一些谷歌搜索结果发现你不能有一个引用 vector ,但我找不到任何关于 unordered_map 的信息。

更新

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

最佳答案

mapunordered_map 可以很好地引用,这里是有效的 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;
}

关于c++ - 以引用为值的 unordered_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24719044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com