C++ Map at()
C++ Mapat()函数
C++映射 at()函数用于通过给定的键访问映射中的元素值。如果所访问的键不存在于地图中,则会抛出异常 _range范围。
语法
考虑键值 k ,语法为:
mapped_type& at (const key_type& k);
const mapped_type& at (const key_type& k) const;
参数
k : 要访问其映射值的元素的键值。
返回值
它使用键值返回对元素映射值的引用。
示例1
让我们看一下一个访问元素的简单示例。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<string,int> m = {
{ "A", 10 },
{ "B", 20 },
{ "C", 30 } };
for (auto& x: m) {
cout << x.first << ": " << x.second << '\n';
}
return 0;
}
输出:
在上面,at()函数用于访问地图元素。
示例2
让我们看一个添加示例的简单示例。元素使用其键值。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<int,string> mymap = {
{ 101, "" },
{ 102, "" },
{ 103, ""} };
mymap.at(101) = "Java";
mymap.at(102) = "T";
mymap.at(103) = "Point";
// prints value associated with key 101, i.e. Java
cout<<mymap.at(101);
// prints value associated with key 102, i.e T
cout<<mymap.at(102);
// prints value associated with key 103, i.e Point
cout<<mymap.at(103);
return 0;
}
输出:
在上面的示例中,使用at()函数在初始化后使用关联的键值添加元素。
示例3
让我们看看一个简单的示例来更改与键值关联的值。
#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<<"Elements are:" <<endl;
for (auto& x: mymap) {
cout << x.first << ": " << x.second << '\n';
}
mymap.at(100) = "Nidhi"; // changes the value associated with key 100 to Nidhi
mymap.at(300) = "Pinku"; // changes the value associated with key 300 to Pinku
mymap.at(500) = "Arohi"; // changes the value associated with key 500 to Arohi
cout<<"\nElements after make changes are:" <<endl;
for (auto& x: mymap) {
cout << x.first << ": " << x.second << '\n';
}
return 0;
}
输出:
Elements are:
100: Nikita
200: Deep
300: Priya
400: Suman
500: Aman
Elements after make changes are:
100: Nidhi
200: Deep
300: Pinku
400: Suman
500: Arohi
在上面的示例中,使用at()函数来更改与其键值关联的值。
示例4
让我们看一个简单的处理"超出范围"的示例
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<char,string> mp = {
{ 'a',"Java"},
{ 'b', "C++" },
{ 'c', "Python" }};
cout<<endl<<mp.at('a');
cout<<endl<<mp.at('b');
cout<<endl<<mp.at('c');
try {
mp.at('z');
// since there is no key with value z in the map, it throws an exception
} catch(const out_of_range &e) {
cout<<endl<<"Out of Range Exception at "<<e.what();
}
输出:
Java
C++
Python
Out of Range Exception at map::at
由于地图中没有值z的键,因此上面的示例引发了out_of_range异常。