持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第13天,点击查看活动详情
1.1 map大小和交换
功能描述:
- 统计map容器大小以及交换map容器
1.2 函数原型:
size();//返回容器中元素的数目empty();//判断容器是否为空swap(st);//交换两个集合容器
1.3 代码示例:
#include <map>
void printMap(map<int,int>&m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key = " << it->first << " value = " << it->second << endl;
}
cout << endl;
}
void test01()
{
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(3, 30));
if (m.empty())
{
cout << "m为空" << endl;
}
else
{
cout << "m不为空" << endl;
cout << "m的大小为: " << m.size() << endl;
}
}
//交换
void test02()
{
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(3, 30));
map<int, int>m2;
m2.insert(pair<int, int>(4, 100));
m2.insert(pair<int, int>(5, 200));
m2.insert(pair<int, int>(6, 300));
cout << "交换前" << endl;
printMap(m);
printMap(m2);
cout << "交换后" << endl;
m.swap(m2);
printMap(m);
printMap(m2);
}
int main() {
test01();
test02();
system("pause");
return 0;
}
1.4 总结:
- 统计大小 --- size
- 判断是否为空 --- empty
- 交换容器 --- swap
1.5 补充说明
1 . map容器:
map容器是关联型容器,键值对应着实值,所有元素根据键值自动排序。
Map中的所有元素都是pair对组,pair的第一个元素为键值,第二个元素为实值,map不允许有相同的键值,但允许有相同的实值。
与set容器一样,不允许通过迭代器修改map的键值,因为键值与map的排列有关,如果修改键值,那么map的结构会被破坏。map的实值是可以修改的。
2. multimap
multimap与map的操作特性类似,位移不同就是multimap允许键值重复。
map和multimap都是用红黑树作为底层实现的。 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的函数