C++ Map

1.3 std::map

std::map 是一种键值对容器,在python中这种容器被称为字典 dict ,在 std::map 中数据都是成对出现的,每一对中的第一个值被称为关键字 key ,每个关键字只能在 std::map 中出现一次,第二个称之为关键的对应值。在使用 std::map 之前,我们需要包含头文件。
#inlcude <map>
using namespace std;	    //如果没有这句,我们在使用时必须指明命名空间std::map

1.3.1 map的定义

std::map 是一个模板类,需要的关键字和存储对象两个模板参数,定义如下:
std::map<关键字的类型名, 存储对象的类型名> 变量名;
类型名可以是各种类型,例如:
std::map<string, int> person; //使用string需要先#include <string> std::map<int, int> mydict;

1.3.2 map的初始化

std::map 可以使用初始化列表 {} 来进行初始化,例如:
std::map<string, int> myMap = { { "One", 1 }, {"Two", 2}, {"Three", 3} };

1.3.3 map的遍历

std::map并不直接支持使用下标进行遍历,因为它是一种按键排序的关联容器,而不是顺序容器。使用下标遍历会导致元素的顺序混乱,不符合 std::map的特性。
  • 使用迭代器遍历
举个例子,初始化一个 std::map然后使用 iterator遍历其中的键值对(key-value pair)
#include <iostream>
#include <string>
#include <map>
using namespace std;

int main()
{
    std::map<string, int> myMap = {{"One", 1}, {"Two", 2}, {"Three", 3}};
    for (std::map<string, int>::iterator it = myMap.begin(); it != myMap.end(); it++)
    {
        cout << "Key: " << it->first << "\tValue: " << it->second << endl;
    }
    return 0;
}
运行结果:
Key: One        Value: 1
Key: Three      Value: 3
Key: Two        Value: 2
在上述示例中,我们使用 myMap.begin() 获取指向第一个键值对的迭代器,使用  myMap.end()  获取指向最后一个键值对后面位置的迭代器。然后,通过迭代器遍历  std::map  中的键值对,并使用  it->first  获取键, it->second  获取值。
上述代码我们在指定迭代器的时候,手动去指定迭代器的类型,这样十分的麻烦,我们可以使用 auto 关键字来自动生成符合条件的迭代器,例如:
#include <iostream>
#include <string>
#include <map>
using namespace std;

int main()
{
    std::map<string, int> myMap = {{"One", 1}, {"Two", 2}, {"Three", 3}};
    for (auto it = myMap.begin(); it != myMap.end(); it++)
    { // 使用auto关键字自动生成迭代器
        cout << "Key: " << it->first << "\tValue: " << it->second << endl;
    }
    return 0;
}
  • 使用范围循环遍历
举个例子,初始化一个 std::map 然后使用 std::pair 遍历其中的键值对(key-value pair)
#include <iostream>
#include <string>
#include <map>
using namespace std;

int main() {
    std::map<string, int> myMap = { { "One", 1 }, {"Two", 2}, {"Three", 3} };
    for (const std::pair<string, int>& pair : myMap) {                        
        cout << "Key: " << pair.first << "\tValue: " << pair.second << endl;
    }
    return 0;
}
运行结果:
Key: One        Value: 1
Key: Three      Value: 3
Key: Two        Value: 2
同样我们也能使用关键字 auto 来自动推导类型
#include <iostream>
#include <string>
#include <map>
using namespace std;

int main() {
    std::map<string, int> myMap = { { "One", 1 }, {"Two", 2}, {"Three", 3} };
    for (auto& pair : myMap) {                        // 使用auto关键字自动生成pair
        cout << "Key: " << pair.first << "\tValue: " << pair.second << endl;
    }
    return 0;
}

1.3.4 map中的元素的访问和修改

可以使用 [] 来访问并修改 std::map 中的元素
#include <iostream>
#include <string>
#include <map>
using namespace std;

int main() {
    std::map<string, int> myMap = { { "One", 1 }, {"Two", 2}, {"Three", 3} };
    myMap["One"] = 10;                                // 修改One对应的值
    for (auto& pair : myMap) {                        // 使用auto关键字自动生成迭代器
        cout << "Key: " << pair.first << "\tValue: " << pair.second << endl;
    }
    return 0;
}
运行结果:
Key: One        Value: 10
Key: Three      Value: 3
Key: Two        Value: 2

1.3.5 map中的常用函数

  • insert(),向map中插入一个键值对,
  • erase(),删除指定键的键值对
  • find(),查找指定键的迭代器
  • count(),返回指定键在map中的出现次数
  • size(),返回map的长度
  • empty(),检查map是否为空
  • clear(),清空map中的所有键值对
  • beign(),返回指向第一个键值对的迭代器
  • end(),返回指向最后一个键值对的迭代器
这里有很多函数的用法于之前介绍 string vector 时的用法类似,这里就不再重复介绍了。
(1)insert()
void std::map<Key, T, Compare, Allocator>::insert(const std::pair<const Key, T>& __x)
std::map  表示  std::map  的模板参数,其中  Key  是键的类型, T  是值的类型, Compare  是用于比较键的比较函数类型, Allocator  是分配器的类型。
而  insert()  函数的原型部分  const std::pair& __x  表示参数  __x  是一个常量引用,类型为  std::pair ,即键值对的类型。
举例说明:
#include <iostream>
#include <string>
#include <map>
using namespace std;

int main() {
    std::map<string, int> myMap = { { "One", 1 }, {"Two", 2}, {"Three", 3} };
    for (auto& pair : myMap) {                        
        cout << "Key: " << pair.first << "\tValue: " << pair.second << endl;
    }
    cout << endl;
    myMap.insert({ "Four", 4 });                    //插入单个键值对
    myMap.insert(pair<string, int>("Five", 5));        //插入std::pair键值对
    myMap.insert(make_pair("Six", 6));                //使用std::make_pair插入键值对
    for (auto& pair : myMap) {
        cout << "Key: " << pair.first << "\tValue: " << pair.second << endl;
    }
    return 0;
}
结果如下:
Key: One        Value: 1
Key: Three      Value: 3
Key: Two        Value: 2

Key: Five       Value: 5
Key: Four       Value: 4
Key: One        Value: 1
Key: Six        Value: 6
Key: Three      Value: 3
Key: Two        Value: 2
(2)erase()
void std::map<Key, T, Compare, Allocator>::erase(const Key& __x)
std::map  表示  std::map  的模板参数,其中  Key  是键的类型, T  是值的类型, Compare  是用于比较键的比较函数类型, Allocator  是分配器的类型。
而  erase()  函数的原型部分  const Key& __x  表示参数  __x  是一个常量引用,类型为  Key ,即要删除的键的类型。
举例说明:
#include <iostream>
#include <string>
#include <map>
using namespace std;

int main() {
    std::map<string, int> myMap = { { "One", 1 }, {"Two", 2}, {"Three", 3}, { "Four", 4 }, {"Five", 5} };
    for (auto& pair : myMap) {                        
        cout << "Key: " << pair.first << "\tValue: " << pair.second << endl;
    }
    cout << endl;
    myMap.erase("Two");                            // 删除指定键的键值对

    auto it = myMap.find("Three");                // 删除指定迭代器指向的键值对
    if (it != myMap.end()) {                    
        myMap.erase(it);
    }
    auto start = myMap.find("Five");            // 删除一定范围内的键值对
    auto end = myMap.find("Four");
    myMap.erase(start, end);                    // 左开右闭

    for (auto& pair : myMap) {
        cout << "Key: " << pair.first << "\tValue: " << pair.second << endl;
    }
    return 0;
}
运行结果:
Key: Five       Value: 5
Key: Four       Value: 4
Key: One        Value: 1
Key: Three      Value: 3
Key: Two        Value: 2

Key: Four       Value: 4
Key: One        Value: 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值