map::operator[]

转载 2016年05月30日 14:52:07

std::map::operator[]

mapped_type& operator[] (const key_type& k);
Access element
If k matches the key of an element in the container, the function returns a reference to its mapped value.

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

A similar member function, map::at, has the same behavior when an element with the key exists, but throws an exception when it does not.

A call to this function is equivalent to:
(*((this->insert(make_pair(k,mapped_type()))).first)).second

Parameters

k
Key value of the element whose mapped value is accessed.
Member type key_type is the type of the keys for the elements stored in the container, defined in map as an alias of its first template parameter (Key).
If an rvalue (second version), the key is moved instead of copied when a new element is inserted.

Return value

A reference to the mapped value of the element with a key value equivalent to k.

Member type mapped_type is the type of the mapped values in the container, defined in map as an alias of its second template parameter (T).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// accessing mapped values
#include <iostream>
#include <map>
#include <string>

int main ()
{
  std::map<char,std::string> mymap;

  mymap['a']="an element";
  mymap['b']="another element";
  mymap['c']=mymap['b'];

  std::cout << "mymap['a'] is " << mymap['a'] << '\n';
  std::cout << "mymap['b'] is " << mymap['b'] << '\n';
  std::cout << "mymap['c'] is " << mymap['c'] << '\n';
  std::cout << "mymap['d'] is " << mymap['d'] << '\n';

  std::cout << "mymap now contains " << mymap.size() << " elements.\n";

  return 0;
}

相关文章推荐

C++语法基础--关联容器--map(一)--constructor,operator[],insert

1关联容器类型        set和map类型的对象所包含的元素都具有不同的键,不允许为同一个键添加第二个元素 2.map类型(#include)   原型:       te...

STL中map的operator[ ]使用方法

在STL中,map是一个关联式容器,它提供一对一的数据处理能力,即其中每一个元素都是一个键值对,通过一个唯一的关键字,可以唯一映射到对应的数据值。而map中重载了下标运算符[],通过下标操作,开发人员...

matrix simple operator

  • 2014年03月19日 17:20
  • 9KB
  • 下载

operator theory

  • 2015年10月23日 13:33
  • 17.91MB
  • 下载

C++读书笔记之重载赋值运算符 overload assignment operator

#include #include using namespace std; class Internet { public: Internet(char *name,char ...

PSSu E F 4DO_operator manual

  • 2015年06月04日 09:46
  • 1.96MB
  • 下载

PSSu E F 4DI_operator manual

  • 2015年06月04日 09:43
  • 1.92MB
  • 下载

为什么operator>>(istream&, string&)能够安全地读入长度未知的字符串?

本文首先试验并分析了栈上定长字符数组输入字符的安全性(char buf[6]; scanf("%s", buf);),然后对operator>>(istream&, string&)的实现细节进行分析...

Zigbee Operator V1.0.0.137

  • 2012年09月16日 18:02
  • 2.67MB
  • 下载

ZigBee Operator

  • 2012年06月02日 18:57
  • 2.79MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:map::operator[]
举报原因:
原因补充:

(最多只允许输入30个字)