【问题标题】:Can a reference type be used as the key type in an STL map引用类型可以用作 STL 映射中的键类型吗
【发布时间】:2010-12-20 05:50:42
【问题描述】:

我可以构造一个std::map,其中键类型是引用类型,例如Foo & 如果没有,为什么不呢?

【问题讨论】:

  • +1 这是一个很多人都不敢问的好问题。
  • 不是直接的,但boost::reference_wrapper<Foo> 应该可以工作。它隐式转换为Foo&

标签: c++ stl types containers


【解决方案1】:

不,因为 std::map 中的许多函数都引用了键类型,而对引用的引用在 C++ 中是非法的。

/A.B.

【讨论】:

    【解决方案2】:

    考虑operator[](const key_type & key)。 如果key_typeFoo & 那么const key_type & 是什么? 问题是它不起作用。您不能构造键类型为引用类型的 std::map。

    【讨论】:

      【解决方案3】:

      根据 C++ 标准 23.1.2/7 key_type 应该是可分配的。引用类型不是。

      【讨论】:

        【解决方案4】:

        指针作为 std::map 的键类型是完全合法的

        #include <iostream>
        #include <cstdlib>
        #include <map>
        
        using namespace std;
        
        
        int main()
        {
        int a = 2;
        int b = 3;
        int * c =  &a;
        int * d =  &b;
        map<int *, int> M;
        
        M[c]=356;
        M[d]=78;
        return 0;
        }
        

        初始化的引用不能是键:

        #include <iostream>
        #include <cstdlib>
        #include <map>
        
        using namespace std;
        
        
        int main()
        {
        int a = 2;
        int b = 3;
        int & c =  a;
        int & d =  b;
        map<int &, int> M;
        
        M[c]=356;
        M[d]=78;
        return 0;
        }
        In file included from /usr/include/c++/4.4/map:60,
                         from test.cpp:3:
        /usr/include/c++/4.4/bits/stl_tree.h: In instantiation of 'std::_Rb_tree<int&, std::pair<int&, int>, std::_Select1st<std::pair<int&, int> >, std::less<int&>, std::allocator<std::pair<int&, int> > >':
        /usr/include/c++/4.4/bits/stl_map.h:128:   instantiated from 'std::map<int&, int, std::less<int&>, std::allocator<std::pair<int&, int> > >'
        test.cpp:14:   instantiated from here
        /usr/include/c++/4.4/bits/stl_tree.h:1407: error: forming pointer to reference type 'int&
        

        '

        【讨论】:

        • 请记住,基于指针的排序是不确定的,并且可能会随着程序的每次调用而改变。
        • 更不用说比较键是否相等,所以这是在查找时比较指针地址值,而不是比较指针值。具体来说,在此示例中,如果有另一个 int e = 2,并且您查找 M[&e],您将不会得到您认为您正在寻找的内容。
        猜你喜欢
        • 1970-01-01
        • 2021-01-14
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        • 2011-11-12
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多