概述:一是使用容器的insert函數(shù)插入元素,使用迭代器訪問元素,該方法是最通用的做法,適用于各種元素類型;二是使用[]插入和訪問元素,要求元素必須是可默認(rèn)構(gòu)造的。
一、使用insert()插入,使用迭代器訪問
#include <iostream>
#include "unordered_map"
using namespace std;
struct student {
string name;
string sex;
int age;
student (string s1, string s2, int i) {
name = s1;
sex = s2;
age = i;
}
};
int main() {
int N;
while (cin >> N) { // 注意 while 處理多個(gè) case
// cout << a + b << endl;
unordered_map <int, student> myMap;
while (N--) {
int num;
string name;
string sex;
int age;
cin >> num >> name >> sex >> age;
myMap.insert(pair<int,student>(num,student(name, sex, age))) ;
}
int M;
cin >> M;
while (M--) {
int num;
cin >> num;
if (myMap.find(num) == myMap.end())
cout << "No Answer!" << endl;
else {
student result = myMap.find(num)->second;
cout << num << ' ' << result.name << ' ' << result.sex << ' ' << result.age <<
endl;
}
}
}
}
// 64 位輸出請(qǐng)用 printf("%lld")
二、使用[]插入和訪問元素,需要注意的是此時(shí)元素必須是可默認(rèn)構(gòu)造的,什么是默認(rèn)可構(gòu)造呢?簡單理解就是不能有構(gòu)造函數(shù),顯然結(jié)構(gòu)體是可默認(rèn)構(gòu)造的。那么如何針對(duì)上文中的student結(jié)構(gòu)體類型實(shí)現(xiàn)下標(biāo)訪問呢,看如下代碼:
#include <iostream>
#include "unordered_map"
using namespace std;
struct student {
string name;
string sex;
int age;
};
int main() {
int N;
while (cin >> N) { // 注意 while 處理多個(gè) case
// cout << a + b << endl;
unordered_map <int, student> myMap;
while (N--) {
int num;
string name;
string sex;
int age;
cin >> num >> name >> sex >> age;
// myMap.insert(pair<int,student>(num,student(name, sex, age))) ;
student temp;
temp.name=name;
temp.age=age;
temp.sex=sex;
myMap[num]=temp;
}
int M;
cin >> M;
while (M--) {
int num;
cin >> num;
if (myMap.find(num) == myMap.end())
cout << "No Answer!" << endl;
else {
student result = myMap[num];
cout << num << ' ' << result.name << ' ' << result.sex << ' ' << result.age <<
endl;
}
}
}
}
// 64 位輸出請(qǐng)用 printf("%lld")
?文章來源地址http://www.zghlxwxcb.cn/news/detail-658713.html文章來源:http://www.zghlxwxcb.cn/news/detail-658713.html
?
到了這里,關(guān)于map及unordered_map插入及訪問元素的兩種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!