key/value pair 形式的集合也可以看作式一个关联式的数组,也即是索引并非整数的数组,因此这两个容器(map,unordered map)都提供了下标操作符[]。
// STL_AssoArray1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main()
{
//type of the container:
//unordered_map:element are key/value pair
//string:keys have type string
//float:values have type float
unordered_map<string, float> coll;
//使用索引语法来插入一些元素
coll["VAT1"] =0.16 ;
coll["VAT2"] =0.07;
coll["Pi"] =3.1415 ;
coll["an arbitrary number"] =4983.223 ;
coll["Null"] = 0;
//change value
coll["VAT1"] += 0.03;
//print difference of VAT values
cout << "VAT difference: " << coll["VAT1"] - coll["VAT2"] << endl;
//也可以使用at()来访问元素的value
coll.at("Pi") = 3.1415926;
//print
for (const auto& elem : coll)
cout << elem.first << ": " << elem.second << endl;
}
运行结果:
VAT difference: 0.12
VAT1: 0.19
Pi: 3.14159
VAT2: 0.07
an arbitrary number: 4983.22
Null: 0