以下是对map容器的讲解: map容器有一个索引值,相当于位置,还有一个就是我们的真值,map容器和set容器一样会自动进行排列,底层也是二叉树。
#include<iostream>
using namespace std;
#include<map>
void print(map<int,int>&m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key值为:" << (*it).first << " " << "初始化的值为: " << it->second << endl;
}
cout << endl;
}
void initializepair()
{
pair<string, int>p1("小刘", 20);
cout << "姓名:" << p1.first << " " << " 年龄:" << p1.second << endl;
pair<string, int>p2 = make_pair("小王", 26);
cout << "姓名:" << p2.first << " " << " 年龄:" << p2.second << endl;
}
void test1()
{
map<int, int>m;
m.insert(pair<int, int>(1, 6));
m.insert(pair<int, int>(3, 8));
m.insert(pair<int, int>(2, 1));
m.insert(pair<int, int>(4, 2));
print(m);
map<int, int>m2(m);
print(m2);
map<int, int>m3;
m3 = m2;
print(m3);
}
void test2()
{
map<int, int>m2;
m2.insert(pair<int, int>(1, 16));
m2.insert(pair<int, int>(3, 18));
m2.insert(pair<int, int>(2, 21));
m2.insert(pair<int, int>(4, 22));
if (m2.empty())
{
cout << "为空!" << endl;
}
else
{
cout << "不为空!" << endl;
}
cout << "大小为:" << m2.size() << endl;
map<int, int>m3;
m3.insert(pair<int, int>(5, 56));
m3.insert(pair<int, int>(6, 58));
m3.insert(pair<int, int>(7, 51));
m3.insert(pair<int, int>(8, 52));
cout << "未交换前:" << endl;
print(m3);
cout << "交换后:" << endl;
m2.swap(m3);
print(m3);
}
void test3()
{
map<int, int>m3;
m3.insert(pair<int, int>(1, 10));
m3.insert(make_pair(2, 20));
m3.insert(map<int, int>::value_type(3, 30));
m3[4] = 40;
print(m3);
m3.erase(m3.begin());
print(m3);
m3.erase(3);
print(m3);
m3.erase(m3.begin(),m3.end());
print(m3);
m3.clear();
print(m3);
}
void test4()
{
map<int, int>m4;
m4.insert(pair<int, int>(1, 11));
m4.insert(make_pair(2, 22));
m4.insert(map<int, int>::value_type(3, 33));
m4[4] = 55;
m4.insert(pair<int, int>(3, 88));
print(m4);
map<int,int>::iterator it=m4.find(4);
if (it != m4.end())
{
cout << "找到了且key和值分别为:" << (*it).first << " " << it->second<<endl;
}
else
{
cout << "没有找到!" << endl;
}
cout << "个数为:" << m4.count(3) << endl;
}
int main()
{
test1();
test2();
test3();
test4();
system("pause");
return 0;
}
希望我的代码能对大家起到一点点的帮助。
|