C++ map类型复习

刚刚复习了c++ map类型,参考博客:cnblogs
1. map类型的插入和遍历:

#include <cstdio>
#include <cstring>
#include <map>
#include <iostream>

using namespace std;

int main()
{
    // 用insert函数插入pair数据 
    map<int, string> mapStudent;
    mapStudent.insert(pair<int, string>(1, "student_one"));
    mapStudent.insert(pair<int, string>(2, "student_two"));
    mapStudent.insert(pair<int, string>(3, "student_three"));



    // 用insert函数插入value_type数据
    mapStudent.insert(map<int, string>::value_type(4, "student_four"));
    mapStudent.insert(map<int, string>::value_type(5, "student_five"));
    mapStudent.insert(map<int, string>::value_type(6, "student_six"));



    //用数组方式插入数据

    mapStudent[7] = "student_seven";
    mapStudent[8] = "student_eigth";
    mapStudent[9] = "student_nine";

    // 数据的遍历 3种方法
    // 用前向迭代器,

    cout<<"forward"<<endl;
    map<int, string>::iterator iterf;
    for (iterf = mapStudent.begin(); iterf != mapStudent.end(); iterf++) {
        cout<<iterf->first<<' '<<iterf->second<<endl;
    }

    // 还有一个反向迭代器

    cout<<"backward"<<endl;
    map<int, string>::reverse_iterator riter;
    for (riter = mapStudent.rbegin(); riter != mapStudent.rend(); riter++) {
        cout<<riter->first<<' '<<riter->second<<endl;
    }


    //数组遍历
    cout<<"array"<<endl;
    int mapSize = mapStudent.size();
    for (int i = 1; i <= mapSize; i++) {
        cout<<i<<' '<<mapStudent[i]<<endl;
    }
    return 0;
}

由于不了解c++里面的value_type这个知识,又查了查,但也只是了解一点还不太深。链接
c++ 中文手册map的介绍:
这里写图片描述
注:find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。

用map类型练练手,题目链接 非常简单,就不添加注释了

#include <cstdio>
#include <iostream>
#include <map>
#include <cstring>
using namespace std;

int main()
{
    int n;
    string str;
    int score;
    while (scanf("%d", &n) != EOF) {
        map<string, int> student;
        map<string, int>::iterator ite;
        for (int i = 0; i < n; i++) {
            cin>>str>>score;
            ite = student.find(str);
            if (ite != student.end()) {
                if (ite->second < score) {
                    student[str] = score;
                }
            }
            else 
                student[str] = score;
        }
        for (ite = student.begin(); ite != student.end(); ite++) {
            cout<<ite->first<<' '<<ite->second<<endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值