unordered_map with reference as value

我们两清 提交于 2019-12-05 07:46:34

map and unordered_map are fine with references, here a working 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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!