Skip to content

Instantly share code, notes, and snippets.

@LincolnBurrows
Last active November 2, 2015 01:23
Show Gist options
  • Save LincolnBurrows/b4da82b837dabe19b041 to your computer and use it in GitHub Desktop.
Save LincolnBurrows/b4da82b837dabe19b041 to your computer and use it in GitHub Desktop.
C++ STL map
声明定义:
#include <map>
std::map<数据类型1,数据类型2> name
key value
for example:
std::map <std::string,int > mapstring;
std::map <std::string,char> mapstring;
添加数据:
map <int,string> maplive;
maplive.insert(pair<int,string>(321,"aclive"));
maplive.insert(map<int,string>::value_type(321,"aclive"));
maplive[321] = "aclive";
查找元素:
map<int,string>::iterator it;
for(it=maplive.begin();it!=maplive.end();++it)
{
int n = it->first;
string s = it->second;
//other operation
}
or
it = maplive.find(321);
if(it==maplive.end())
cout<<"can not find 112\n";
else
maplive.erase(it); //delete 112
排序:
Map中的元素是自动按key升序排序,所以不能对map用sort函数
其他方法:
begin() 返回指向map头部的迭代器
end() 返回指向map末尾的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
equal_range() 返回特殊条目的迭代器
erase() 删除一个元素
find() 查找一个元素
insert() 插入元素
get_allocator() 返回map的配置器
key_comp() 返回比较元素key的函数
value_comp() 返回比较元素value的函数
lower_bound() 返回键值>=给定元素的第一个位置
upper_bound() 返回键值>给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
size() 返回map中元素的个数
swap() 交换两个map
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment