C++ Map常见用法说明
2017-08-01 10:54
274 查看
map简介
C++中map提供的是一种键值对容器,里面的数据都是成对出现的,如下图:每一对中的第一个值称之为关键字(key),每个关键字只能在map中出现一次;第二个称之为该关键字的对应值。map中常用的方法
clear() 删除所有元素insert() 插入元素
size() 返回map中元素的个数
#include<iostream> #include<map> using namespace std; int main() { std::map<int,int> m; for(int i=0; i<10; i++) { m[i]=i;//写题时,通常这样插入 } m.insert(std::pair<int, int>(10, 100));//没这样插入过 for(int i=0; i<=10; i++) cout<<m[i]<<" "; cout<<endl; int sum=m.size(); cout<<"map内元素的数量为sum="<<m.size()<<endl; m.clear();//清空 sum=m.size(); cout<<"清空后sum="<<sum<<endl; return 0; }
begin() 返回指向map头部的迭代器
end() 返回指向map末尾的迭代器
find(x) 返回查找一个元素的迭代器下(x为下标)
count() 返回指定元素出现的次数(非0即1,你懂的)
empty() 如果map为空则返回true
era
4000
se(x) 删除一个元素(x为下标)
lower_bound(x) 返回键值>=给定元素的第一个位置(x为下标)
upper_bound(x) 返回键值>给定元素的第一个位置(x为下标)
swap() 交换两个map
#include<iostream> #include<map> using namespace std; int main() { std::map<int,int> m; std::map<int,int> mp; for(int i=0; i<10; i++) { m[i]=i+1;//写题时,通常这样插入 } m[10]=1; map<int,int>::iterator t1=m.begin(); for(; t1!=m.end(); ++t1) cout<< t1->first <<"==>"<< t1->second <<endl; cout<<"1是否出现"<<m.count(1)<<endl; if(!m.empty()) cout<<"map中不为空"<<endl; cout<<"下标为5的元素为="<<m.find(5)->second<<endl; m.erase(5); cout<<"删除下标为5的元素后"<<endl; for(t1=m.begin(); t1!=m.end(); ++t1) cout<< t1->first <<"==>"<< t1->second <<endl; cout<<"大于等于(下标6)的第一个元素的位置和数 "<<m.lower_bound(6)->first<<"==>"<<m.lower_bound(6)->second<<endl; cout<<"大于(下标6)的第一个元素的位置和数 "<<m.upper_bound(6)->first<<"==>"<<m.upper_bound(6)->second<<endl; mp[0]=1000; m.swap(mp); cout<<"m数组元素为"<<endl; map<int,int>::iterator it; for(it=m.begin();it!=m.end();it++) cout<<it->first<<"==>"<<it->second<<endl; cout<<"mp数组元素为"<<endl; for(it=mp.begin();it!=mp.end();it++) cout<<it->first<<"==>"<<it->second<<endl; return 0; }
转载:http://blog.csdn.net/zxy160/article/details/76461724
相关文章推荐
- C++ Map常见用法说明
- C++ Map常见用法说明
- C++ Map常见用法说明
- C++ Map常见用法说明
- C++ STL之map常见用法
- C++ Map/Multimap 常见用法全解(代码版)
- C++中的map常见用法
- c++中的map用法详解
- C++ list, vector, map, set 区别与用法比较
- map函数,java和C++的常见用法
- 【C/C++】联合union的用法和说明
- c++ list, vector, map, set 区别与用法比较
- C++ map的基本操作和用法
- C++学习笔记---再探 map 的用法之计数重复key的value值的方法,由leetcode 169题想到的
- C++中map容器的说明和使用技巧
- C++ 标准模板库STL中map用法介绍
- C++--------------------------------------Map的基础用法
- C++中map的详细用法
- c++ stl中map容器的基本用法
- C++序列容器之 vector常见用法总结