1.map基本概念
2.map构造和赋值
#include
using namespace std;
#include
void printMap(const map<int, int>& m)
{
for (map<int, int>::const_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>(3, 30));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(4, 40));
printMap(m);
map<int, int>m2(m);
printMap(m2);
map<int, int>m3;
m3 = m2;
printMap(m3);
}
int main()
{
test01();
system("pause");
return 0;
}
3.map大小和交换
#include
using namespace std;
#include
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>(3, 30));
m.insert(pair<int, int>(2, 20));
if (m.empty())
{
cout << "m为空!" << endl;
}
else
{
cout << "size of m : " << m.size() << endl;
}
}
void test02()
{
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(3, 30));
m.insert(pair<int, int>(2, 20));
map<int, int>m2;
m2.insert(pair<int, int>(4, 100));
m2.insert(pair<int, int>(6, 300));
m2.insert(pair<int, int>(5, 200));
cout << "交换前:" << endl;
printMap(m);
printMap(m2);
m.swap(m2);
cout << "交换后:" << endl;
printMap(m);
printMap(m2);
}
int main()
{
test01();
cout << "-------------" << endl << endl;
test02();
system("pause");
return 0;
}
4.map插入和删除
#include
using namespace std;
#include
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(make_pair(2, 20));
m.insert(map<int, int>::value_type(3, 30));
m[4] = 40;
5.map查找和统计
#include
using namespace std;
#include
void test01()
{
map<int, int>m;
m.insert(make_pair(1, 10));
m.insert(make_pair(3, 30));
m.insert(make_pair(2, 20));
m.insert(make_pair(2, 40));
map<int, int>::iterator pos = m.find(3);
if (pos != m.end())
{
cout << "找到了该元素 key = " << (*pos).first << " value = " << pos->second << endl;
}
else
{
cout << "no find this element" << endl;
}
int num = m.count(2);
cout << "num = " << num << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
6.map容器排序
#include
using namespace std;
#include
class MyCompare
{
public:
bool operator()(int v1, int v2) const
{
return v1 > v2;
}
};
void test01()
{
map<int, int, MyCompare> m;
m.insert(make_pair(1, 10));
m.insert(make_pair(3, 30));
m.insert(make_pair(2, 20));
for (map<int, int, MyCompare>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key = " << it->first << " value = " << it->second << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}