114.STL中的map

114.STL中的map

1.map的简介

map是C++STL中的一个关联式容器,它提供一对一的hash,它类似于Python中的字典,也有着键值对(Key-Value)这一说。我们可以通过键(Key)来找到值(Value),但需要注意的是,每个键(Key)只能在map中出现一次哦!

map可以储存多种类型的数据,它主要用于一对一映射的情况,map内部的实现是通过自建一颗红黑树,这颗树可以对数据进行自动排序。所以在map内部所有的数据都是有序的,这个功能以后可以方便我们解决很多问题。

使用map时需要包含头文件:

#include<map>

2.map的定义及初始化

定义map<数据类型1,数据类型2>变量名
例:

//map的定义 
map<int,int> m1; //定义一个Key数据类型为int,Value数据类型为int的map容器m1 
map<double,double> m2; //定义一个Key数据类型为double,Value数据类型为double的map容器m2 
map<int,string> m3; //定义一个Key数据类型为int,Value数据类型为string的map容器m3

3.迭代器

begin   返回指向容器起始位置的迭代器(iterator) 
end      返回指向容器末尾位置的迭代器 
cbegin    返回指向容器起始位置的常迭代器(const_iterator) 
cend    返回指向容器末尾位置的常迭代器 

代码:

//unordered_map::bucket_count
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

int main()
{
    unordered_map<string, string> mymap =
    {  
        {"house", "maison"},      
        {"apple", "pomme"},   
        {"tree", "arbre"},
        {"book", "livre"},
        {"door", "porte"},
        {"grapefruit", "pamplemousse"}
    };
  
    /************begin和end迭代器***************/
    cout << "mymap contains:";
  
    for (auto it = mymap.begin(); it != mymap.end(); ++it)
        cout << " " << it->first << ":" << it->second;
    cout << endl;

    /************bucket操作***************/
    unsigned n = mymap.bucket_count();
    cout << "mymap has " << n << " buckets.\n";
    for (unsigned i = 0; i < n; ++i)
    {
        cout << "bucket #" << i << "'s size:" << mymap.bucket_size(i) << " contains: ";
        for (auto it = mymap.begin(i); it != mymap.end(i); ++it)
             cout << "[" << it->first << ":" << it->second << "] ";
        cout << "\n";
    }
    cout << "\nkey:'apple' is in bucket #" << mymap.bucket("apple") << endl;
    cout << "\nkey:'computer' is in bucket #" << mymap.bucket("computer") << endl;

    return 0;
}

输出:

mymap contains: house:maison apple:pomme tree:arbre book:livre door:porte grapefruit:pamplemousse
mymap has 8 buckets.
bucket #0's size:1 contains: [book:livre]
bucket #1's size:1 contains: [door:porte]
bucket #2's size:1 contains: [grapefruit:pamplemousse]
bucket #3's size:1 contains: [house:maison]
bucket #4's size:0 contains:
bucket #5's size:1 contains: [tree:arbre]
bucket #6's size:0 contains:
bucket #7's size:1 contains: [apple:pomme]

key:'apple' is in bucket #7

key:'computer' is in bucket #0

4.Capacity操作

size     返回有效元素个数 
max_size  返回 unordered_map 支持的最大元素个数 
empty      判断是否为空 

5.元素访问

operator[]       访问元素 
at         访问元素 
#include<iostream>
#include<map>
using namespace std;
int main()
{
	map<int, string> m1;
	m1[1] = "ctx";
	m1[2] = "cxt";
	m1[3] = "txc";
	m1[10] = "txt";
	m1[5] = "666";
	map<int, string>::iterator it;
	for (it = m1.begin(); it != m1.end(); it++)
	{
		cout << it->first << " " << it->second << endl;
	}
	//it->为Key,it->second为Value 

	return 0;
}

输出:

1 ctx
2 cxt
3 txc
5 666
10 txt

6.查找

unordered_map<string, double>::const_iterator got = myrecipe.find("coffee");

if (got == myrecipe.end())
    cout << "not found";
else
    cout << "found " << got->first << " is " << got->second << "\n\n";

7.元素修改

insert    插入元素 
erase   删除元素 
swap    交换内容 
clear     清空内容 
emplace  构造及插入一个元素 
emplace_hint 按提示构造及插入一个元素 

插入:

unordered_map < string, double> myrecipe, mypantry = { {"milk",2.0},{"flour",1.5} };
/****************插入*****************/

pair<string, double> myshopping("baking powder", 0.3);
myrecipe.insert(myshopping);                        // 复制插入
myrecipe.insert(make_pair<string, double>("eggs", 6.0)); // 移动插入
myrecipe.insert(mypantry.begin(), mypantry.end());  // 范围插入
myrecipe.insert({ {"sugar",0.8},{"salt",0.1} });    // 初始化数组插入(可以用二维一次插入多个元素,也可以用一维插入一个元素)
myrecipe["coffee"] = 10.0;  //数组形式插入
 myrecipe.emplace("apple", 5.0);//构造及插入一个元素 

删除:

myrecipe.erase(myrecipe.begin());  //通过位置
myrecipe.erase("milk");    //通过key
display(myrecipe, "After erase myrecipe contains:");

交换:

myrecipe.swap(mypantry);
display(myrecipe, "After swap with mypantry, myrecipe contains:");

修改:

/****************修改*****************/
myrecipe.at("coffee") = 9.0;
myrecipe["milk"] = 3.0;
display(myrecipe, "After modify myrecipe contains:");

清空:

myrecipe.clear();
display(myrecipe, "After clear, myrecipe contains:");

完整代码:

// unordered_map::insert
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

void display(unordered_map<string, double> myrecipe, string str)
{
    cout << str << endl;
    for (auto& x : myrecipe)
        cout << x.first << ": " << x.second << endl;
    cout << endl;
}

int main()
{
    unordered_map < string, double> myrecipe, mypantry = { {"milk",2.0},{"flour",1.5} };
    /****************插入*****************/

    pair<string, double> myshopping("baking powder", 0.3);
    myrecipe.insert(myshopping);                        // 复制插入
    myrecipe.insert(make_pair<string, double>("eggs", 6.0)); // 移动插入
    myrecipe.insert(mypantry.begin(), mypantry.end());  // 范围插入
    myrecipe.insert({ {"sugar",0.8},{"salt",0.1} });    // 初始化数组插入(可以用二维一次插入多个元素,也可以用一维插入一个元素)
    myrecipe["coffee"] = 10.0;  //数组形式插入
    myrecipe.emplace("apple", 5.0);

    display(myrecipe, "myrecipe contains:");
    /****************查找*****************/
    unordered_map<string, double>::const_iterator got = myrecipe.find("coffee");

    if (got == myrecipe.end())
        cout << "not found";
    else
        cout << "found " << got->first << " is " << got->second << "\n\n";

    /****************修改*****************/
    myrecipe.at("coffee") = 9.0;
    myrecipe["milk"] = 3.0;
    display(myrecipe, "After modify myrecipe contains:");

    /****************擦除*****************/
    myrecipe.erase(myrecipe.begin());  //通过位置
    myrecipe.erase("milk");    //通过key
    display(myrecipe, "After erase myrecipe contains:");

    /****************交换*****************/
    myrecipe.swap(mypantry);
    display(myrecipe, "After swap with mypantry, myrecipe contains:");

    /****************清空*****************/
    myrecipe.clear();
    display(myrecipe, "After clear, myrecipe contains:");

    return 0;
}

输出:

found coffee is 10

After modify myrecipe contains:
baking powder: 0.3
eggs: 6
flour: 1.5
apple: 5
milk: 3
sugar: 0.8
salt: 0.1
coffee: 9

After erase myrecipe contains:
eggs: 6
flour: 1.5
apple: 5
sugar: 0.8
salt: 0.1
coffee: 9

After swap with mypantry, myrecipe contains:
milk: 2
flour: 1.5

After clear, myrecipe contains:

8.操作

find       通过给定主键查找元素,没找到:返回unordered_map::end
count      返回匹配给定主键的元素的个数 
equal_range   返回值匹配给定搜索值的元素组成的范围 

9.Buckets

bucket_count    返回槽(Bucket)数 
max_bucket_count    返回最大槽数 
bucket_size       返回槽大小 
bucket       返回元素所在槽的序号 
load_factor     返回载入因子,即一个元素槽(Bucket)的最大元素数 
max_load_factor    返回或设置最大载入因子 
rehash       设置槽数 
reserve        请求改变容器容量

参考:[详细介绍C++STL:unordered_map](详细介绍C++STL:unordered_map - 朤尧 - 博客园 (cnblogs.com))

posted @ 2023-07-23 14:28  CodeMagicianT  阅读(19)  评论(0编辑  收藏  举报