分析C++中map插入及访问元素的两种方式的使用条件:迭代器和下标

概述:一是使用容器的insert函数插入元素,使用迭代器访问元素,该方法是最通用的做法,适用于各种元素类型;二是使用[]插入和访问元素,要求元素必须是可默认构造的。

一、使用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 处理多个 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 位输出请用 printf("%lld")

二、使用[]插入和访问元素,需要注意的是此时元素必须是可默认构造的,什么是默认可构造呢?简单理解就是不能有构造函数,显然结构体是可默认构造的。那么如何针对上文中的student结构体类型实现下标访问呢,看如下代码:

#include <iostream>
#include "unordered_map"
using namespace std;
struct student {
    string name;
    string sex;
    int age;
    
    
};
int main() {
    int N;
    while (cin >> N) { // 注意 while 处理多个 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 位输出请用 printf("%lld")

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值