【问题标题】:unordered_map with reference as value以引用为值的 unordered_map
【发布时间】:2014-09-03 08:05:32
【问题描述】:

值类型为引用 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 无关,因为它是我的代码中的一个错误。

【问题讨论】:

  • 只需使用std::reference_wrapper
  • 你可以声明这样一个地图,并且大多数但不是所有的操作都应该工作。您不能使用operator[],因为它要求映射类型为DefaultConstructible(并且引用不是)。您不能大括号初始化此映射,或将一个映射分配给另一个映射,因为这要求映射类型为 CopyAssignable
  • @Igor 大多数容器不需要 (Copy/Move)Assignable,它们可以与 (Copy/Move)Constructible 一起正常工作,并且赋值或大括号初始化很好。 map 的 operator[] 是唯一需要 DefaultConstructible 和 (Copy/Move)Assignable 的例外。
  • @galop1n 好吧,对于特定的编译器和标准库实现,这可能不是必需的。但是利用这种灵活性的程序不是有效的 C++11 程序。实际上,它是不可移植的;它恰好可以与此实现一起使用,但不能保证与其他符合要求的实现一起使用。
  • @IgorTandetnik 你应该回答你的第一条评论,它非常有用,我很乐意支持它。

标签: c++ c++11 stl reference unordered-map


【解决方案1】:

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

【讨论】:

  • 似乎不适用于对象。用 std::thread 试试这个只会给我error: value-initialization of reference type ‘std::thread&amp;’
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 2021-01-22
  • 2014-12-30
相关资源
最近更新 更多