C++ STL中map的用法及统计数组各个元素出现的次数

map的基本用法
  1. 变量声明
map<string ,string> m; //可以使任意类型,包括自定义类型
  1. 插入元素
m.insert(pair<string,string>("key","value"));
  1. 查找元素
iter = m.find("key");

if(iter != m.end())
       cout<<"Find, the value is"<<iter->second<<endl;
else
   cout<<"Do not Find"<<endl;
  1. 删除或者清空
//用关鍵字刪除
int n = m.erase("key");//如果刪除了会返回1,否則返回0

//用迭代器范围刪除 : 把整个map清空
m.erase(m.begin(), m.end());
//等同于m.clear()
统计数组(或者向量)中各元素出现的次数
#include <map>
int main(void)
{
    int i;
    int a[] = { 1, 2, 3, 4, 5, 5, 5 };
    map<int, int> m;
    for (i = 0; i < 7; i++)
    {
        if (m.end() != m.find(a[i])) m[a[i]]++;
        else m.insert(pair<int, int>(a[i], 1));
    }
    for (auto it : m)
    {
        cout << it.first << ends << it.second << endl;
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值