STL常用容器-pair对组&map/multimap容器

pair对组创建

功能描述:

成对出现的数据,利用对组可以返回两个数据;

pair中第一个元素为key(键值),起到索引的作用,第二个元素是value值(实际值)

两种创建方式:

pair<type, type> p(value1, value2);

pair<type, type> p = make_pair(value1, value2);

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

// 对组创建使用
void test01()
{
	// 利用构造函数直接创建对组
	pair<string, int> p1("tom", 20);
	pair<string, int>p2 = make_pair("jerry", 21);

	// 访问对组中的key值和value值
	cout << p1.first << ":" << p1.second << endl;
	cout << p2.first << ":" << p2.second << endl;
}

map基本概念

特点:

map中所有的元素都是对组pair

pair中第一个元素为key(键值),起到索引作用,第二个元素为value(实值)

所有的元素都会根据key值来进行自动排序

map存储结构和set一样的都是基于红黑树的,所以map不能修改key值,但是可以修改value值

可以使用map[key]来获取key值对应的value值,at(key)也能获取

不支持随机存取,因为不是连续的物理空间,所以迭代器不能进行算术运算,只能进行++或者--

本质:

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

优点:

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

map和multimap区别:

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

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

map的常用函数

map构造和赋值

功能描述:对map容器进行构造和赋值操作

构造:

map<T1, T2> mp; // 默认构造

map(const map&mp) // 拷贝构造

map<T1,T2, 仿函数> mp; // 仿函数来制定排序规则,默认是以key值为准进行升序排序

赋值:

map& operator=(const map&mp); //重载等号操作符

取值:

可以用map[key]的方式获取key对应的value值, at(key)也可以

// 声明一个通用的打印函数 需要使用C++11新特性实现
template<class T1, class T2>
void printMap(map<T1, T2>& m)
{
	for (auto p : m)
	{
		cout << p.first << ":" << p.second << endl;
	}
}

void test02()
{
	// 创建一个新的map容器
	map<int, int> m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(3, 30));
	m.insert(pair<int, int>(4, 40));
	//printMap(m);

	// 拷贝构造
	map<int, int> m1(m);
	//printMap(m1);

	//赋值
	map<int, int> m2;
	m2 = m1;
	//printMap(m2);

	// 插入元素
	m.insert(make_pair(5, 50));
	m[6] = 60;
	//printMap(m);

	// 取值
	cout << "key = 3:" << m[3] << endl;
	cout << "key = 3:" << m.at(3) << endl;
	m[3] = 300;
	//printMap(m);

	// 删除元素
	m.erase(m.begin());
	printMap(m);
	m.erase(m.begin(), ++m.begin());
	printMap(m);
	
	m.erase(6);
	printMap(m);
}

总结:

map中所有元素都是成对出现,插入数据时候要使用对组。

map插入和删除

功能描述: map容器进行插入数据和删除数据

函数原型:

insert(elem); // 在容器中插入元素,返回插入元素的迭代器

map[key] // key存在时是修改value,如果不存在是添加key和value(不建议)

clear() // 清空容器

erase(pos) // 删除pos迭代器所指的元素,返回下一个元素的迭代器

erase(beg,end) // 删除区间[beg,end)中的元素,返回下一个元素的迭代器

erase(key); // 删除容器中值为key的元素

void printMap(map<int,int>&m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key = " << it->first << " value = " << it->second << endl;
}
cout << endl;
}
void test01()
{

//插入
map<int, int> m;

//第一种插入方式
m.insert(pair<int, int>(1, 10));

//第二种插入方式
m.insert(make_pair(2, 20));

//第三种插入方式
m.insert(map<int, int>::value_type(3, 30));

//第四种插入方式
m[4] = 40;
printMap(m);

//删除
m.erase(m.begin());
printMap(m);
m.erase(3);
printMap(m);

//清空
m.erase(m.begin(),m.end());
m.clear();
printMap(m);

}

总结:

map插入方式很多,记住其一即可

插入 --- insert

删除 --- erase

清空 --- clear

迭代器失效的问题

map和multimap只有在删除当前的iterator的时候才会失效,只要在erase时,更新迭代器即可,插入和删除不会对其他节点造成影响

插入操作不会导致任何迭代器失效

// 迭代器失效
// 只有删除会导致迭代器失效,需要更新,插入数据的时候并不会引起迭代器失效
void test03()
{
	map<int, int> m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(3, 30));

	for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
	{
		if ((*it).first == 2)
		{
			it = m.erase(it);
		}
	}
	printMap(m);
}

map的大小和交换

功能描述: 统计map容器大小以及交换map容器

函数原型:

size() // 返回容器中元素的个数

empty() // 判断容器是否为空

swap(st) // 交换两个集合容器

void printMap(map<int,int>&m)
{
    for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
    cout << "key = " << it->first << " value = " << it->second << endl;
}
    cout << endl;
}

void test01()
{
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(3, 30));
if (m.empty())
{
cout << "m为空" << endl;
}
else
{
cout << "m不为空" << endl;
cout << "m的大小为: " << m.size() << endl;
}
}

//交换
void test02()
{
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(3, 30));

map<int, int>m2;
m2.insert(pair<int, int>(4, 100));
m2.insert(pair<int, int>(5, 200));
m2.insert(pair<int, int>(6, 300));

cout << "交换前" << endl;

printMap(m);
printMap(m2);

cout << "交换后" << endl;

m.swap(m2);

printMap(m);
printMap(m2);
}

总结:

统计大小 --- size

判断是否为空 --- empty

交换容器 --- swap

map的查找和统计

功能描述: 对map容器进行查找数据以及统计数据

函数原型:

find(key); // 查找key是否存在,如果存在就返回该键的元素的迭代器,如果不存在就返回map.end();

count(key); // 查找容器中有多少个key元素个数,对于map而言只能是0或者是1

//查找和统计
void test01()
{
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(3, 30));
//查找
map<int, int>::iterator pos = m.find(3);
if (pos != m.end())
{
cout << "找到了元素 key = " << (*pos).first << " value = " << (*pos).second << endl;
}
else
{
cout << "未找到元素" << endl;
}
//统计
int num = m.count(3);
cout << "num = " << num << endl;
}

总结:

查找 --- find (返回的是迭代器)

统计 --- count (对于map,结果为0或者1)

map容器根据key来排序

功能描述:map容器默认排序规则为 按照key值进行 从小到大排序

主要技术点:

利用仿函数可以指定map容器的排序规则

对于自定义类型,map必须指定排序规则,同set容器

// 利用仿函数改变默认排序规则
class myCompare
{
public:
	// 在类中重载()运算符
	bool operator()(int v1, int v2) const // 和set规则一致
	{
		return v1 > v2;
	}
};

void test06()
{
	map<int, int, myCompare> m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(3, 30));

	for (auto p : m)
	{
		cout << p.first << ":" << p.second << endl;
	}
}

// map容器根据value值来进行排序
// 根据value值来排序,通过vector容器,将map容器转化为vector,然后利用排序算法sort来实现
bool paiSort(pair<string, int> &p1, pair<string, int> &p2)
{
	return p1.second > p2.second; // 根据年龄进行排序
}

void test07()
{
	map<string, int> mp;
	mp.insert(make_pair("tom", 18));
	mp.insert(make_pair("jerry", 8));
	mp.insert(make_pair("dijia", 12));
	printMap(mp);
	
	// 使用vector来对value值进行排序,需要将map中所有的对组放到vector中
	vector<pair<string, int>> v(mp.begin(), mp.end());
	// 利用算法sort来对vector中的元素排序
	sort(v.begin(), v.end(), paiSort);

	for (auto p : v)
	{
		cout << p.first << ":" << p.second << endl;
	}
}

总结:

利用仿函数可以指定map容器的排序规则

对于自定义数据类型,map必须要指定排序规则,同set容器

修改multimap中相同的key键对应的某个value值

// multimap中key值可以重复,那么如果直接用[]来修改value值会有问题 
void test05()
{
	multimap<string, int> mp;
	mp.insert(make_pair("tom", 20));
	mp.insert(make_pair("tom", 10));
	mp.insert(make_pair("lucy", 18));
	mp.insert(make_pair("jerry", 25));
	mp.insert(make_pair("jerry", 8));
	mp.insert(make_pair("tom", 40));

	for (auto ele : mp)
	{
		cout << ele.first << ":" << ele.second << endl;
	}

	// 既然key有可能出现重复的情况,那么就可以通过find()和count()来获取有多少相同的key,然后再去选择修改哪一个key
	int mCount = mp.count("tom"); // 先查找有几个tom
	multimap<string, int>::iterator pos = mp.find("tom"); // 找到第一个tom
	for (int i = 0; i < mCount; i++)
	{
		cout << pos->first << ":" << pos->second << endl;
		pos++;
	}
	
}


// 修改multimap中相同的key键对应的某个value值
void test03()
{
	multimap<string, int> mp;
	mp.insert(make_pair("tom", 18));
	mp.insert(make_pair("dijia", 18));
	mp.insert(make_pair("tom", 28));
	mp.insert(make_pair("tom", 38));

	// equal_range()  返回pair对象,其中first和second成员会全部转化为迭代器
	// 所以可以进行遍历,遍历时通过second的值来进行判断, 符合条件的直接修改当前迭代器对应的second值
	auto range = mp.equal_range("tom");
	for (auto it = range.first; it != range.second; it++)
	{
		// 找到要修改的tom对应的28.,改为100即可
		if (it->second == 28)
		{
			it->second = 100;
		}
	}

	for (auto it = range.first; it != range.second; it++)
	{
		cout << it->first << " : " << it->second << endl;
	}
}

map的练习

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

// 求交集
// 输入s1 = {1,3,6,9}  s2 = {1,2,6,11};
// 输出 {1,6}

set<int> checkSame(set<int>& s1, set<int>& s2)
{
	set<int> st;
	// 遍历集合,判断第一个集合中的数字是否在第二个结合中出现
	for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
	{
		if (s2.find(*it) != s2.end())
		{
			st.insert(*it);
		}
	}
	return st;
}


void test01()
{
	set<int> s1 = { 1,3,6,9 }, s2 = { 1,2,6,11 };
	set<int> res = checkSame(s1, s2);
	for (auto ele : res)
	{
		cout << ele << " ";
	}
	cout << endl;
}


// map存储两种类型的数据,string用户名, User是用户对象,name,pwd
// 查找用户是否存在,如果不存在就新增用户,并且密码初始化为8888, 如果用户存在就将密码直接初始化为8888

// 创建User对象
class User
{
public:
	string name;
	string pwd;
	User(string name, string pwd) :name(name), pwd(pwd) {}
};

void resetPwd(map<string, User>& muser, string username)
{
	map<string, User>::iterator pos = muser.find(username);
	if (pos == muser.end()) //没有找到
	{
		User u(username, "8888");
		muser.insert(make_pair(username, u));
	}
	else
	{
		(*pos).second.pwd = "8888";
	}
}

void test02()
{
	User u1("tom", "1111"), u2("jerry", "2222"), u3("lucy", "3333");
	map<string, User> mp;
	mp.insert(make_pair("tom", u1));
	mp.insert(make_pair("jerry", u2));
	mp.insert(make_pair("lucy", u3));

	resetPwd(mp, "lucy"); // lucy已经存在就直接重置密码
	resetPwd(mp, "dijia"); // dijia不存在就新增迪迦用户,并且初始化密码为8888

	for (auto ele : mp)
	{
		cout << ele.first << " : " << ele.second.pwd << endl;
	}
}

  • 24
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ STL中的mapmultimap是关联容器,用于存储键值对(key-value pairs),其中每个键(key)唯一对应一个值(value)。 map是一个有序容器,根据键的大小进行自动排序,默认按照键的升序进行排序。每个键只能在map中出现一次,如果尝试插入具有相同键的元素,新元素将替代旧元素。 multimap也是一个有序容器,与map不同的是,它允许多个具有相同键的元素存在。多个具有相同键的元素将按照插入的顺序进行存储,而不会自动排序。 这两个容器都提供了一系列的操作函数,如insert、erase、find等,用于插入、删除和查找元素。 以下是一个使用map的简单示例: ```cpp #include <iostream> #include <map> int main() { std::map<std::string, int> scores; scores.insert(std::make_pair("Alice", 90)); scores.insert(std::make_pair("Bob", 80)); scores.insert(std::make_pair("Charlie", 70)); // 查找并输出Bob的分数 std::cout << "Bob's score: " << scores["Bob"] << std::endl; // 遍历并输出所有键值对 for (const auto& pair : scores) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; } ``` 上述示例中,我们创建了一个存储string类型键和int类型值的map容器scores。通过insert函数依次插入了三个键值对。然后我们通过scores["Bob"]来获取Bob的分数,并输出结果为80。 接着我们使用范围-based for循环遍历map中的所有键值对,并输出每个键值对的键和值。 multimap的用法与map类似,只是它允许多个具有相同键的元素存在。 这些关联容器在查找和插入操作上具有较高的效率,特别适用于需要根据键进行快速查找的场景。在实际应用中,你可以根据自己的需求选择适合的容器类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值