相关疑难解决方法(0)

map operator []的返回值(以及"at"方法)

我有以下示例代码来解释我的问题.根据STD地图容器文档(http://www.cplusplus.com/reference/map/map/operator%5B%5D/),operator [](或"at"方法)返回对映射值的引用.我明白为什么第13行编译并正常工作(当我将元素插入vec1时,映射中的映射值会更新).我不明白为什么第13行不会导致编译错误,因为vec1不是引用而operator []返回引用.

  1 #include <map>
  2 #include <vector>
  3
  4 using namespace std;
  5
  6 int main()
  7 {
  8     map<int, vector<int> > port;
  9
 10     port[1] = vector<int>(1, 10);
 11
 12     vector<int> &vec1 = port[1];    // <===
 13     vector<int> vec2 = port[1];   // <===
 14
 15     return 0;
 16 }
Run Code Online (Sandbox Code Playgroud)

我想也许operator []的实际实现被重载以返回两种类型(值和引用).但是,当我查看"map"头文件时,它似乎没有(除非我遗漏了一些东西):

文件:/usr/include/c++/4.7/profile/map.h

      // 23.3.1.2 element access:
      mapped_type&
      operator[](const key_type& __k)
      {
        __profcxx_map_to_unordered_map_find(this, size());
        return _Base::operator[](__k);
      }

#ifdef __GXX_EXPERIMENTAL_CXX0X__
      mapped_type&
      operator[](key_type&& __k)
      {
        __profcxx_map_to_unordered_map_find(this, size());
        return _Base::operator[](std::move(__k)); …
Run Code Online (Sandbox Code Playgroud)

c++ stl map c++11

2
推荐指数
1
解决办法
654
查看次数

标签 统计

c++ ×1

c++11 ×1

map ×1

stl ×1