C ++ map operator []函数用于使用给定键值访问map中的元素。
它类似于at()函数。它们之间的唯一区别是,如果map中不存在所访问的键,则抛出异常;另一方面,如果map中不存在该键,则operator[]将键插入map中。
考虑键值k,语法为:
mapped_type& operator[] (const key_type& k); // 在 C++ 11 之前 mapped_type& operator[] (const key_type& k); //从 C++ 11 开始 mapped_type& operator[] (key_type&& k); //从 C++ 11 开始
k:访问其map值的元素的键值。
它使用键值返回对元素map值的引用。
让我们看一个访问元素的简单示例。
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char, int> m = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
cout << "Map包含以下元素" << endl;
cout << "m['a'] = " << m['a'] << endl;
cout << "m['b'] = " << m['b'] << endl;
cout << "m['c'] = " << m['c'] << endl;
cout << "m['d'] = " << m['d'] << endl;
cout << "m['e'] = " << m['e'] << endl;
return 0;
}输出:
Map包含以下元素 m['a'] = 1 m['b'] = 2 m['c'] = 3 m['d'] = 4 m['e'] = 5
在上面,operator []函数用于访问map的元素。
让我们看一个简单的示例,使用它们的键值添加元素。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<int,string> mymap = {
{ 101, "" },
{ 102, "" },
{ 103, ""} };
mymap[101] = "nhooo";
mymap[102] = ".";
mymap[103] = "com";
//打印与键101相关联的值,即nhooo
cout<<mymap[101];
// 打印与键102相关的值,即.
cout<<mymap[102];
//打印与键103相关的值,即com
cout<<mymap[103];
return 0;
}输出:
(cainiaojc.com)
在上面的示例中,operator []用于在初始化后使用关联的键值添加元素。
让我们看一个简单的示例,以更改与键值关联的值。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<int,string> mymap = {
{ 100, "Nikita"},
{ 200, "Deep" },
{ 300, "Priya" },
{ 400, "Suman" },
{ 500, "Aman" }};
cout<<"元素是:" <<endl;
for (auto& x: mymap) {
cout << x.first << ": " << x.second << '\n';
}
mymap[100] = "Nidhi"; //将与键100关联的值更改为Nidhi
mymap[300] = "Pinku"; //将与键300关联的值更改为Pinku
mymap[500] = "Arohi"; //将与键500关联的值更改为Arohi
cout<<"\n更改后的元素是:" <<endl;
for (auto& x: mymap) {
cout << x.first << ": " << x.second << '\n';
}
return 0;
}输出:
元素是: 100: Nikita 200: Deep 300: Priya 400: Suman 500: Aman 更改后的元素是: 100: Nidhi 200: Deep 300: Pinku 400: Suman 500: Arohi
在上面的示例中,operator []函数用于更改与其键值关联的值。
让我们看一个简单的实例来区分operator []和at()。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<char,string> mp = {
{ 'a',"Java"},
{ 'b', "C++" },
{ 'c', "Python" }};
cout<<endl<<mp['a'];
cout<<endl<<mp['b'];
cout<<endl<<mp['c'];
mp['d'] = "SQL";
cout<<endl<<mp['d'];
try {
mp.at('z');
//由于map中没有值为z的键,因此会抛出异常
} catch(const out_of_range &e) {
cout<<endl<<"\n超出范围异常 "<<e.what();
}
return 0;
}输出:
Java C++ Python SQL 超出范围异常 map::at
在上面的示例中,当我们使用at()函数时,它会抛出out_of_range异常,因为映射中没有值z的键,而当我们使用operator []在键值d中添加元素时,因为没有键在map中值为“ d”的情况下,它将在map中插入键为“ d”且值为“ SQL”的键值对。