STL之map容器代码详解

基础概念

在这里插入图片描述
简介:

  • map中所有元素都是pair。
  • pair中第一个元素为key(键值),起到索引作用,第二个元素为value(实值)。
  • 所有元素都会根据元素的键值自动排序。

本质:

map/multimap属于关联式容器,底层结构是用二叉树实现。

优点:

可以根据key值快速找到value值。

map和multimap区别

map不允许容器中有重复key值元素;

multimap允许容器中有重复key值元素。

代码示例

Talk is cheap, show me the code.

#include<iostream>
using namespace std;
#include<map>

void printMap(const map<int, int>& mm)
{
	for (map<int, int>::const_iterator it = mm.begin(); it != mm.end(); it++)
	{
		cout << "Key is: " << (*it).first << "Value is: " << (*it).second << endl;
	}
}

/*
构造:
map<T1, T2> mp; //map默认构造函数:
map(const map &mp); //拷贝构造函数
赋值:
map& operator=(const map &mp); //重载等号操作符
*/

void test01()
{
	map<int, int> mp;
	mp.insert(pair<int, int>(1, 10));
	mp.insert(pair<int, int>(2, 20));
	mp.insert(pair<int, int>(3, 30));
	mp.insert(pair<int, int>(4, 40));

	printMap(mp);

	map<int, int> mp2(mp);
	printMap(mp2);

	map<int, int> mp3;
	mp3 = mp2;
	printMap(mp3);
}

/*
大小和交换函数原型:
size(); //返回容器中元素的数目
empty(); //判断容器是否为空
swap(st); //交换两个集合容器
*/

void test02()
{
	map<int, int> mp;
	mp.insert(pair<int, int>(1, 10));
	mp.insert(pair<int, int>(2, 20));
	mp.insert(pair<int, int>(3, 30));
	mp.insert(pair<int, int>(4, 40));

	printMap(mp);

	if (mp.empty())
	{
		cout << "Empty!" << endl;
	}
	else
	{
		cout << mp.size() << endl;
	}

	map<int, int> mp2;
	mp2.insert(pair<int, int>(5, 50));
	cout << "Swap Before: " << endl;
	printMap(mp);
	printMap(mp2);
	cout << "Swap After: " << endl;
	mp.swap(mp2);
	printMap(mp);
	printMap(mp2);
}

/*
插入和删除函数原型:
insert(elem); //在容器中插入元素。
clear(); //清除所有元素
erase(pos); //删除pos迭代器所指的元素,返回下一个元素的迭代器。
erase(beg, end); //删除区间[beg,end)的所有元素 ,返回下一个元素的迭代器。
erase(key); //删除容器中值为key的元素。
*/

void test03()
{
	map<int, int> mp;
	mp.insert(pair<int, int>(1, 10));
	mp.insert(pair<int, int>(2, 20));
	mp.insert(pair<int, int>(3, 30));
	mp.insert(pair<int, int>(4, 40));
	printMap(mp);

	map<int, int>::iterator it = mp.begin();
	mp.erase(it);
	printMap(mp);

	mp.erase(3);
	printMap(mp);

	mp.erase(mp.begin(), mp.end());
	printMap(mp);
}

/*
map查找和统计函数原型:
find(key); //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();
count(key); //统计key的元素个数
*/

void test04()
{
	map<int, int> mp;
	mp.insert(pair<int, int>(1, 10));
	mp.insert(pair<int, int>(2, 20));
	mp.insert(pair<int, int>(3, 30));
	mp.insert(pair<int, int>(4, 40));
	printMap(mp);

	if (mp.find(3)!=mp.end())
	{
		cout << "Exists: " << (*mp.find(3)).second << endl;
	}
	else
	{
		cout << "Not Exists" << endl;
	}

	int num = mp.count(3);
	cout << num << endl;
}

/*
map容器排序:
利用仿函数,可以改变排序规则
*/
class myCompare
{
public:
	bool operator()(int val1,int val2)const //这里需要加const
	{
		return val1 > val2;
	}
};

void test05()
{
	map<int, int,myCompare> mp;
	mp.insert(pair<int, int>(1, 10));
	mp.insert(pair<int, int>(2, 20));
	mp.insert(pair<int, int>(3, 30));
	mp.insert(pair<int, int>(4, 40));

	for (map<int, int,myCompare>::const_iterator it = mp.begin(); it != mp.end(); it++)
	{
		cout << "Key is: " << (*it).first << "Value is: " << (*it).second << endl;
	}

}

int main()
{
	test01();
	test02();
	test03();
	test04();
	test05();
	system("pause");
	return 0;
}

应用场景

C++的STL(标准模板库)中的map容器是一个关联容器,它提供了键值对的存储和检索功能,其中每个键都是唯一的。map基于红黑树实现,因此它在查找、插入和删除操作上具有较好的性能。以下是map容器在实际项目中的一些常见应用场景的例子:

  1. 字典/词典
    map常用于实现字典或词典的功能,其中键表示单词,值表示对应的释义、定义或其他相关信息。这在文本处理、自然语言处理等应用中很常见。

    #include <iostream>
    #include <map>
    #include <string>
    
    int main() {
        std::map<std::string, std::string> dictionary;
    
        // 添加词条
        dictionary["apple"] = "a fruit";
        dictionary["book"] = "a set of written or printed pages, usually bound with a protective cover";
        dictionary["car"] = "a four-wheeled motor vehicle used for transportation";
    
        // 查找释义
        std::cout << "Meaning of 'book': " << dictionary["book"] << std::endl;
    
        return 0;
    }
    
    
  2. 配置管理
    在项目中,map可用于存储配置信息,其中键是配置项的名称,而值是对应的配置值。这样可以方便地进行配置管理和查找。

    #include <iostream>
    #include <map>
    #include <string>
    
    int main() {
        std::map<std::string, std::string> config;
    
        // 添加配置项
        config["username"] = "john_doe";
        config["password"] = "secretpassword";
        config["server_address"] = "127.0.0.1";
    
        // 获取配置项
        std::cout << "Username: " << config["username"] << std::endl;
    
        return 0;
    }
    
    
  3. 计数器/统计
    map可以用于实现计数器,其中键是要计数的项目,而值是计数值。这在数据分析、统计学等领域中非常有用。

    #include <iostream>
    #include <map>
    #include <vector>
    
    int main() {
        std::map<int, int> counter;
        std::vector<int> data = {1, 2, 3, 2, 1, 3, 4, 5, 1, 2, 4, 4, 5};
    
        // 统计每个元素出现的次数
        for (const auto& item : data) {
            counter[item]++;
        }
    
        // 输出统计结果
        for (const auto& pair : counter) {
            std::cout << pair.first << ": " << pair.second << " times" << std::endl;
        }
    
        return 0;
    }
    
    

这些例子只是map在实际项目中应用的冰山一角,map的灵活性和高效性使得它在许多场景下都是一个强大的工具。在实际项目中,根据需要选择合适的容器是很重要的,map通常在需要快速查找、插入和删除的情况下是一个不错的选择。

实际用例

假设我们有一个简单的任务,需要统计一段文本中每个单词出现的次数。我们可以使用map容器轻松完成这个任务。以下是一个简单的C++代码示例:

#include <iostream>
#include <map>
#include <sstream>
#include <string>

int main() {
    // 输入文本
    std::string inputText = "This is a simple example. This example demonstrates the usage of map in a project.";

    // 使用istringstream分割单词
    std::istringstream iss(inputText);
    std::map<std::string, int> wordCount;

    std::string word;
    while (iss >> word) {
        // 将单词添加到map中,如果已存在则增加计数
        wordCount[word]++;
    }

    // 输出每个单词的出现次数
    std::cout << "Word frequencies:" << std::endl;
    for (const auto& pair : wordCount) {
        std::cout << pair.first << ": " << pair.second << " times" << std::endl;
    }

    return 0;
}

在这个示例中,我们使用map容器存储每个单词和其出现的次数。通过遍历文本并使用istringstream分割单词,我们可以很方便地统计每个单词的出现次数。map的优势在于它可以快速查找并更新每个单词的计数,而不需要复杂的手动管理数据结构。

这样的例子展示了在项目中使用map容器来解决实际问题时,它的简洁性和高效性。在更大规模的项目中,这种便捷的数据结构可以帮助提高代码的可读性和维护性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值