C++ Maps
C++ Maps是一种关联式容器,包含“关键字/值”对
使用map时必须的包:(下面的例子代码,使用的是万能头文件,它其包含map包)
#include <map>
#include <bits/stdc++.h> //万能头文件
函数:
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的函数
为了后续函数方便,这里先介绍一下迭代器
迭代器:
迭代器可被用来访问一个容器类的所包函的全部元素,其行为像一个指针。举一个例子,你可用一个迭代器来实现对vector容器中所含元素的遍历。
如用迭代器遍历vector数组求和:
#include<bits/stdc++.h>
using namespace std;
int main() {
vector<int> the_vector;
vector<int>::iterator the_iterator; //定义一个vector迭代器
for( int i=0; i < 10; i++ )
the_vector.push_back(i);
int total = 0;
the_iterator = the_vector.begin();
while( the_iterator != the_vector.end() ) {
total += *the_iterator; //指针取值,即*the_iterator
the_iterator++;
}
cout << "Total=" << total << endl;
return 0;
}
其结果就是
Total=45
Map
同理,迭代器遍历map
例子:
#include<bits/stdc++.h>
using namespace std;
int main() {
//这里的string表示关键字,int为关键字的值
//当然你也可以用map<int,int>来定义,那前一个int为关键字,后一个int为关键字的值;
//这里定义什么类型都行,结构体也行
map<string, int> maps;
maps["hi"]=1; //为关键字“hi” 赋值为 1
maps["hello"]=2;
map< string,int>::iterator iter; //map的迭代器
for(iter = maps.begin(); iter != maps.end(); iter++)
cout<<iter->first<<' '<<iter->second<<endl;//输出的是key value值
return 0;
}
map是自动排序的,按字字典的顺序自动排序的,所以输出结果是按照关键字字典顺序输出的:
hello 2
hi 1
map再程序设计竞赛中有着很大的用处,尤其是处理字符串标记时。
下面是使用map题目:
题目1
题目2
题目3
欢迎大家批评改正!!!