当前位置:网站首页>STL容器——map的基本操作
STL容器——map的基本操作
2022-07-17 05:04:00 【哆啦k梦0219】
map简介
map是STL的一个关联容器,以键值对存储数据,其类型可以自己定义,每个关键字在map中只能出现一次,关键字不能修改,值可以修改,map主要用于资料一对一映射。map是内部有序的(自动排序,单词时按照字母序排序),查找的时间复杂度为O(logn)。
一、map的定义(声明)
基本结构为map<关键字类型,值类型>
map<string,int> my_map1;
map<int,int> my_map2;
二、基本操作
1.插入数据
第一种:用insert函数插入pair数据:
map<int,string> my_map;
my_map.insert(pair<int,string>(1,"first"));
my_map.insert(pair<int,string>(2,"second"));第二种:数组的方式直接赋值:
map<int,string> my_map;
my_map[1]="first";
my_map[4]="second";
遍历:
map<int,string>::iterator it;
for(it=my_map.begin();it!=my_map.end();it++)
cout<<it->first<<it->second<<endl;
针对第二种插入数据的方法,给出示例如下:
这是一个统计字符串字母数量的程序(区分大小写) :
#include <iostream>
#include <map>
#include <cstring>
using namespace std;
int main()
{
char str[100] = { 0 };
cin.getline(str, sizeof(str));
map<char,int> maps;
for(int i=0;i<strlen(str);i++)
{
if(isalpha(str[i]))
maps[str[i]]++;
}
for(auto it = maps.begin();it!=maps.end();it++)
{
cout<<it->first<<":"<<it->second<<endl;
}
return 0;
}2.查找元素
第一种:用 count(关键字) 函数来判断关键字是否出现,其缺点是无法定位元素出现的位置。count函数的返回值要么是0,要么是1。
map<string,int> m;
m["first"]=1;
cout<<m.count("first")<<endl; //输出1,表示关键字“first”存在
第二种:用 find(关键字) 函数来定位元素出现的位置,它返回一个迭代器(指针),当数据出现时,返回的是数据所在位置的迭代器;若map中没有要查找的数据,返回的迭代器等于end()函数返回的迭代器。
迭代器it->first 代表关键字 it->second代表值
// find 返回迭代器指向当前查找元素的位置否则返回m.end()位置
iter = m.find("123");
if(iter != m.end()) //m.end()返回map的末尾地址,实际上该地址越界.
cout<<"Find, the value is"<<iter->second<<endl;
else
cout<<"Cannot Find"<<endl;
3.删除元素与清空元素
//迭代器刪除
iter = m.find("123");
m.erase(iter);
//用关键字刪除
int n = m.erase("123"); //刪除成功返回1,否则返回0
//用迭代器范围刪除 : 把整个map清空
m.erase(mapStudent.begin(), mapStudent.end());
//等同于m.clear()
4.map的大小
int Size = m.size();
三.unordered_map
unordered_map的底层基于哈希表实现的,基本操作和map一致。区别是unordered_map内部是无序的。
优点: 查找,删除 添加的速度快,时间复杂度为常数级0(c)
下面是利用哈希表的一个题例:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:输入:nums = [3,3], target = 6
输出:[0,1]来源:力扣LeetCode1.两数之和
链接:https://leetcode.cn/problems/two-sum
代码如下(C++):
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};map的遍历
可采用迭代器遍历:
for(auto it = maps.begin();it!=maps.end();it++)
{
cout<<it->first<<":"<<it->second<<endl;
}边栏推荐
- Travel data acquisition, data analysis and data mining [2022.5.30]
- Harmonyos入门
- 异步数据-短信验证码
- 学习C语言的第五天
- 02_電影推薦(ContentBased)_用戶畫像
- 【C语言—零基础第十一课】旋转大转盘之指针
- 02 Bar _ Recommandation de film (basée sur le contenu) Portrait de l'utilisateur
- mysql数据库实验实训6,数据视图(详细)
- 租用服务器,以及部署在pycharm专业版上的pytorch环境训练yolov5模型教程服务器环境安装库文件:
- 02_ Movie recommendation (contentbased)_ User portrait
猜你喜欢

Cve-2017-12635 CouchDB vertical privilege bypass vulnerability recurrence

Pygame:外星人入侵

SMS verification test without signature template audit

CVE-2019-14234 Django JSONField SQL注入漏洞

Elment UI usage

About the current response, the method getoutputstream() has been called

CVE-2022-23131 Zabbix SAML SSO认证绕过漏洞

数据分析与数据挖掘实战案例本地房价预测(716):

ModelArts第二次培训笔记

Flask的使用
随机推荐
学习C语言第三天
上传七牛云的方法
Feature extraction of machine learning (digitization and discretization of category features and digitization of text features)
Cve-2017-12635 CouchDB vertical privilege bypass vulnerability recurrence
mysql数据库实验实训5,数据查询yggl数据库查询(详细)
Fanoutexchange switch is simple to use
安装MySQL
Learn about scheduled tasks in one article
Use of flask
POC——DVWA‘s SQL Injection
3. Restclient query document
简单快速建立pytorch环境YOLOv5目标检测 模型跑起来(超简单)
数据可视化
用户管理-分页
Redis installation
Teddy Cup title a full version optimization update (4/23)
Chat about global filter
游玩数据获取与数据分析、数据挖掘 【2022.5.30】
MySQL takes the union of two query conditions and then queries
[2022 10th Teddy Cup Challenge] Title A: complete version of pest identification (general idea. Detailed process and code and results CSV in compressed package)