moc 发表于 2018-9-21 20:29:45

051-C++之STL-->map、multimap

本帖最后由 moc 于 2018-9-21 20:29 编辑

1、map、multimap简介
   1. map是标准的关联式容器, 一个map是一个键值对序列,即(key,value)对,它提供基于key的快速检索能力,类似于python中的字典dict。
   2. map中的key值是唯一的。该容器中的元素是按一定的顺序排列,元素插入的过程是按照排序规则插入的,所以不能指定插入位置。
   3. map的具体实现采用红黑树变体的平衡二叉树的数据结构。在插入和删除操作上比vector快。
   4. multimap与map的区别:map支持唯一键值,每个键只能出现一次,而multimap中相同的键可以出现多次,且multimap不支持[]操作。
   5. #include <map>
2、map插入元素的四种方式
前三种方法返回值为一个对组,即pair<iterator, bool>_Pairib。
map<int, string> map1;

// 方法1
map1.insert(pair<int, string>(1, "teacher01"));
map1.insert(pair<int, string>(2, "teacher02"));

// 方法2
map1.insert(make_pair(3, "teacher03"));
map1.insert(make_pair(4, "teacher04"));

// 方法3
map1.insert(map<int, string>::value_type(5, "teacher05"));
pair<map<int, string>::iterator, bool> mypair1 = map1.insert(map<int, string>::value_type(6, "teacher06"));
if (mypair1.second == true)
{
        cout << "插入成功!\n";
}
else
{
        cout << "插入失败!\n";
}

// 方法4
map1 = "teacher07";
map1 = "teacher08";

// 容器的遍历
for (map<int, string>::iterator it = map1.begin(); it != map1.end(); it++)
{
        cout << it->first << '\t' << it->second << endl;
}

for (auto each : map1)
{
        cout << each.first << '\t' << each.second << endl;
}
// map容器元素的删除
while (!map1.empty())
{
        map<int, string>::iterator it = map1.begin();
        map1.erase(it);
}
3、map基本操作
map的查找键 (含异常处理)
map<int, string>::iterator it = map1.find(100);
if (it == map1.end())
{
        cout << "key 100的值 不存在\n";
}
else
{
        cout << it->first << '\t' << it->second << endl;
}
方法:equal_range(n),返回两个迭代器 形成一个pair,pair中第一个为大于等于n的迭代器位置,第二个为大于n的迭代器位置。
pair<map<int, string>::iterator, map<int, string>::iterator> mypair = map1.equal_range(5);
if (mypair.first == map1.end())
{
        cout << "第一个迭代器>= 5的位置不存在\n";
}
else
{
        cout << mypair.first->first << '\t' << mypair.first->second << endl;

}
if (mypair.second == map1.end())
{
        cout << "第二个迭代器>5的位置不存在\n";
}
else
{
        cout << mypair.second->first << '\t' << mypair.second->second << endl;
}
4、multimap一键多值举例
Staff s1("Tom1", 18), s2("Tom2", 23), s3("Jhon1", 24), s4("Jhon2", 18), s5("Alice", 20);
multimap<string, Staff> map3;

map3.insert(make_pair("Tom", s1));
map3.insert(make_pair("Tom", s2));

map3.insert(make_pair("Jhon", s3));
map3.insert(make_pair("Jhon", s4));

map3.insert(make_pair("Alice", s5));

for (auto each : map3)
{
        cout << each.second.name << '\t' << each.second.age << endl;
}

int num = map3.count("Jhon");
cout << "名为Jhon的个数:" << num << endl;
multimap<string, Staff>::iterator it = map3.find("Jhon");

int tag = 0;
while (it != map3.end() && tag < num)
{
        cout << it->first << '\t' << it->second.name << endl;
        it++;
        tag++;
}

cout << "按照条件检索:\n";
for (multimap<string, Staff>::iterator it = map3.begin(); it != map3.end(); it++)
{
        if (it->second.age == 20)
        {
                cout << "年龄为20的是: " << it->second.name << endl;
        }
}
页: [1]
查看完整版本: 051-C++之STL-->map、multimap