C++ STL MAP学习
1、简介
map是关联容器(associative container),用来存储由对构成的元素。在一个map中,Key用来唯一标识元素和排序,Value存储与Key值关联的实际数据。这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。 map中根据Kay值查找元素的时间复杂度是O(log n),这个根据上面的红黑树存储结构可推倒得到。 Key可以是任意类型,但该类型必须是可以比较的。如果是自定义类型,则必须重写比较函数:
inline bool compare(const keytype &key,const keytype &key)
2、功能
- 自动建立Key -Value的对应, key 和 value可以是任意你需要的类型。
- 根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次, 1,000,000个记录,最多查找20次。
- 快速插入Key – Value 记录。
- 快速删除记录
- 根据Key 修改value记录。
- 遍历所有记录。
3、map的使用
3.1、初始化 使用map需要的include stl的头文件
include <map> // stl 头文件
举个例子说明,一个班级中,每个学生的学号跟他的姓名就存在着一一映射的关系,这个模型用map可能轻易描述,很明显学号用int描述,姓名用字符串描述(本篇文章中不用char *来描述字符串, 而是采用STL中string来描述),下面给出map描述代码:
map<int, string>mapStudent;
我们再建立一个string为Key的map,如下:
map<string, int>mapTest;
3.2、在map中插入元素
1
使用[ ]运算符
mapStudent[1] = "wnag;"
mapTest["aaa"] = 101;
上述两个操作都是先查找map中是否存在该Key值,如果存在则修改该Key对应的Value,如果不存在则插入map中。
2
mapStudent.insert(std::pair<int, string>(2, "zhang"));
mapTest.insert(std::pair<string, int>("bbb", 102));
也可以使用如下的insert函数
mapStudent.insert(map<int, string>::value_type(1, "li"));
mapTest.insert(map<string, int>::value_type("ccc", 103));
但是在使用insert函数时,如果插入的key值已经存在,则插入不成功。这是与使用[ ]运算符的区别。 遇到这样的问题时,可以使用pair来获得是否插入成功,程序如下 pair<map::iterator, bool> Insert_Pair; Insert_Pair = mapStudent.insert(map::value_type(1, "zhang")); / 我们通过pair的第二个变量来知道是否插入成功,它的第一个变量返回的是一个map的迭代器, * 如果插入成功的话Insert_Pair.second应该是true的,否则为false。 / if(true == Insert_Pair.secont) std::cout << "Insert success !" << std::endl; else std::cout << "Insert key exist !" << std::endl;
3.3、在map中查找元素
1
使用[ ]运算符 查找键为K的元素
string name = mapStudent[1];
如K在map中,则返回其对应的Value的引用。 如果K不在map中,则会插入在map中插入一个新的元素,这个元素的Key是K,Value是一个默认的值,并且返回这个Value的应用。需要注意的是,如果这种操作发生,那么map的size总会加一,即使没有指定的Value值(元素由默认的构造函数构造)。
2
find( ) 函数
iterator find (const key_type &k);
搜索Key值为K的元素,如果找到的话返回指向该元素的iterator,否则返回指向map::end的iterator。通过map对象的方法获取的iterator数据类型是一个std::pair对象,包括两个数据 iterator->first 和 iterator->second 分别代表关键字和存储的数据 map::iterator iter = mapTest.find("so"); printf("%s \n", iter == mapTest.end() ? "Not find! " : "Find!"); if(mapTest.end() != iter) std::cout << iter->first << " " << iter->second << std::endl;
3
count( )函数
size_type count (const key_type &k)const;
搜索Key值为K的元素并且返回匹配的个数。因为map中包含的key是唯一的,所以如果找到返回1,没找到返回0。 如果找到相应元素,则可以使用[ ]运算符输出该Key对应的Value。 if(mapTest.cout("aaa"))
相比与find,count在map中做了两次查找(count运算一次,[]操作一次),耗时更多。
3.4、删除元素
调用map::erase() 函数,函数声明有如下三个 void erase(iterator position); size_type erase(const key_type &k); void erase(iterator first, iterator last);
void clear() noexcept; //清空整个map
第一个函数删除iter所指向的位置; 第二个函数依据提供的Key值做删除,函数返回值为删除元素个数(0或者1,0表示没有找到相应元素) 第三个函数删除一个range的元素,删除从first到last的元素,包含first不包含last map::iterator it; it = mapTest.find("aaa"); mapTest.erase(it); //erasing by iterator
mapTest.erase("bbb"); // erasing by key
it = mapTest.find("ccc");
myTest.erase(it, mapTest.end()); // eraseing by range
myStudent.clear();
3.5、map的遍历
map<string, int>::itreator itTest = mapTest.begin();
map<int, string>::iterator itStudent = mapStudent.begin();
for(; itTest != mapTest.end() ; itTest++)
std::cout << itTest->first << " " << itTest->second << std::endl;
/* itTest->first 的值为Key,itTest->second的值为Value */
3.6、swap两个map中的数据
swap函数交换两个容器的内容,这两个map类型需要相同,但是大小可以不同。 // swap maps #include #include
foo['x']=100;
foo['y']=200;
bar['a']=11;
bar['b']=22;
bar['c']=33;
foo.swap(bar);
std::cout << "foo contains:\n";
for (std::map<char,int>::iterator it=foo.begin(); it!=foo.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
std::cout << "bar contains:\n";
for (std::map<char,int>::iterator it=bar.begin(); it!=bar.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
return 0;
}
3.7、其他常用函数
-
1
at() 函数 at()函数同[ ]操作符 mapStudent.at(1) = "zhao"; mapStudent[1] = "zhao1"; -
2
size()函数,返回map中元素的个数 3
empty()函数 如果map中不含元素,则返回true,否则返回false
Map是c++的一个标准容器,她提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果,总结了一些map基本简单实用的操作!
1、map最基本的构造函数
map<string , int >mapstring; map<int ,string >mapint;
map<sring, char>mapstring; map< char ,string>mapchar;
map<char ,int>mapchar; map<int ,char >mapint;
2、map添加数据
map<int ,string> maplive;
1. maplive.insert(pair<int,string>(102,"aclive"));
2. maplive.insert(map<int,string>::value_type(321,"hai"));
3. maplive[112]="April"; //map中最简单最常用的插入添加!
3、map中元素的查找
find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。
map<int ,string >::iterator l_it;;
l_it=maplive.find(112);
if(l_it==maplive.end())
std::cout << "we do not find 112" << std::endl;
else
std::cout << "wo find 112" << std::endl;
4、map中元素的删除
如果删除112;
map<int ,string >::iterator l_it;;
l_it=maplive.find(112);
if(l_it==maplive.end())
cout<<"we do not find 112"<<endl;
else
maplive.erase(l_it); //delete 112;
5、map中 swap的用法
Map中的swap不是一个容器中的元素交换,而是两个容器交换;
For example:
#include <map>
#include <iostream>
using namespace std;
int main( )
{
map <int, int> m1, m2, m3;
map <int, int>::iterator m1_Iter;
m1.insert ( pair <int, int> ( 1, 10 ) );
m1.insert ( pair <int, int> ( 2, 20 ) );
m1.insert ( pair <int, int> ( 3, 30 ) );
m2.insert ( pair <int, int> ( 10, 100 ) );
m2.insert ( pair <int, int> ( 20, 200 ) );
m3.insert ( pair <int, int> ( 30, 300 ) );
cout << "The original map m1 is:";
for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
cout << " " << m1_Iter->second;
cout << "." << endl;
// This is the member function version of swap
//m2 is said to be the argument map; m1 the target map
m1.swap( m2 );
cout << "After swapping with m2, map m1 is:";
for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
cout << " " << m1_Iter -> second;
cout << "." << endl;
cout << "After swapping with m2, map m2 is:";
for ( m1_Iter = m2.begin( ); m1_Iter != m2.end( ); m1_Iter++ )
cout << " " << m1_Iter -> second;
cout << "." << endl;
// This is the specialized template version of swap
swap( m1, m3 );
cout << "After swapping with m3, map m1 is:";
for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
cout << " " << m1_Iter -> second;
cout << "." << endl;
}
6.map的sort问题
Map中的元素是自动按key升序排序,所以不能对map用sort函数:
For example:
#include <map>
#include <iostream>
using namespace std;
int main( )
{
map <int, int> m1;
map <int, int>::iterator m1_Iter;
m1.insert ( pair <int, int> ( 1, 20 ) );
m1.insert ( pair <int, int> ( 4, 40 ) );
m1.insert ( pair <int, int> ( 3, 60 ) );
m1.insert ( pair <int, int> ( 2, 50 ) );
m1.insert ( pair <int, int> ( 6, 40 ) );
m1.insert ( pair <int, int> ( 7, 30 ) );
cout << "The original map m1 is:"<<endl;
for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
cout << m1_Iter->first<<" "<<m1_Iter->second<<endl;
}
The original map m1 is:
1 20
2 50
3 60
4 40
6 40
7 30
请按任意键继续. . .
7、map的基本操作函数
C++ Maps是一种关联式容器,包含“关键字/值”对
begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
end() 返回指向map末尾的迭代器
equal_range() 返回特殊条目的迭代器对
erase() 删除一个元素
find() 查找一个元素
get_allocator() 返回map的配置器
insert() 插入元素
key_comp() 返回比较元素key的函数
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
size() 返回map中元素的个数
swap() 交换两个map
upper_bound() 返回键值>给定元素的第一个位置
value_comp() 返回比较元素value的函数