STL_映射_【map】

map是STL的一个关联容器,它提供一对一的数据处理能力。(其中第一个可以称为关键字,
每个关键字只能在map中出现一次,第二个可以称为该关键字的值)
比方说 字典, 统计单词

下面就通过简单易懂的代码对其讲解

#include <iostream>
#include <map>
using namespace std;
//构造方法 int char float double string 甚至结构体 都可以任意搭配
map <string, int> month;
map <int, char> m;
struct node //结构体类型
{
    string name;
    float score;
    //从小到大
    bool operator < (const node &a) const
    {
        return a.score > score;
    }
};


int main()
{
    // 赋值方式
    month["January"] = 1;
    month["February"] = 2;
    month["July"] = 7;
    // 迭代器
    map <string, int>::iterator  it;

    for(it = month.begin(); it != month.end(); ++ it)
    {
        //两种方式
        cout << it -> first << " " << it -> second << endl;
        cout << (*it).first << " " << (*it).second << endl;
    }
    ///map 的大小
    int l = month.size();
    cout << "map 的数据个数:" << l << endl;

    /// find 查找键值 返回位置
    m[25] = 'm';
    m[47] = 's';
    map <int, char>::iterator t = m.find(25);//查找键值, 返回位置。
    if(t != m.end())
    {
        cout << (*t).first << ":" << (*t).second << endl;
    }
    else
    {
        cout << "not find !" << endl;
    }

    /// 结构体形式 可实现排序功能
    map<node, int> m1;
    node n;
    n.name = "Jack";
    n.score = 87.6;
    m1[n] = 45;
    n.name = "Tom";
    n.score = 90.0;
    m1[n] = 46;
    n.name = "Timi";
    n.score = 66.6;
    m1[n] = 47;
    for(map<node, int> :: iterator it1 = m1.begin(); it1 != m1.end(); ++ it1)
    {
        cout << (*it1).second << endl;
        cout << ((*it1).first).name << " " << ((*it1).first).score << endl;
    }

    return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值