一 . 概述
map中所有的容器都是pair(即键值对) pair中的第一个元素为key(键值),起到索引的作用,第二个元素为value值 map和multimap的区别: map不允许容器中有重复的key值 mutimap中允许容器中有重复的key值
二 . 构造与赋值
#include<iostream>
#include<string>
#include<map>
using namespace std;
void PrintMap(map<int, string>& m)
{
for (map<int, string>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "Key euqals " << (*it).first << endl <<"Value equals " << (*it).second;
}
}
int main()
{
map<int, string> mapStudent1;
mapStudent1.insert(pair<int, string>(000, "student_one"));
map<int, string> mapStudent2(mapStudent1);
PrintMap(mapStudent1);
PrintMap(mapStudent2);
return 0;
}
三 . 对元素的操作
#include<iostream>
#include<string>
#include<map>
using namespace std;
class Mycompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
void PrintMap(map<int, int>& m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "Key euqals " << (*it).first << endl <<"Value equals " << (*it).second;
}
std::cout << endl;
}
void EmptyandSwap(map<int, int>& m1, map<int, int>& m2)
{
cout << "the size of m1 is " << m1.size() << endl;
if (m1.empty())
cout << "m1 is empty" << endl;
m1.insert(pair<int, int>(1, 10));
m2.insert(pair<int, int>(4, 40));
PrintMap(m1);
PrintMap(m2);
cout << endl;
m1.swap(m2);
PrintMap(m1);
PrintMap(m2);
}
void EraseandClear(map<int, int>& m1)
{
m1.insert(pair<int, int>(1, 10));
m1.insert(pair<int, int>(2, 20));
m1.erase(m1.begin());
m1.erase(2);
m1.clear();
}
void FindandCount(map<int, int>& m1)
{
m1.insert(pair<int, int>(1, 10));
m1.insert(pair<int, int>(2, 20));
m1.insert(pair<int, int>(3, 30));
map<int, int>::iterator pos = m1.find(1);
if (pos != m1.end())
cout << "find this element" << endl;
else
cout << "Not found" << endl;
int number = m1.count(3);
cout << number << endl;
}
void changeline(map<int, int,Mycompare>& m1)
{
m1.insert(pair<int, int>(1, 10));
m1.insert(pair<int, int>(2, 20));
m1.insert(pair<int, int>(3, 30));
for (map<int, int,Mycompare>::iterator it = m1.begin(); it != m1.end(); it++)
{
cout << "Key euqals " << (*it).first << endl << "Value equals " << (*it).second;
}
std::cout << endl;
}
int main()
{
return 0;
}
|