Contenedores STL de uso común: introducción y uso de contenedores de mapas

1. Introducción al contenedor de mapas

El contenedor de mapa es un contenedor asociativo que almacena pares de clave-valor de tipo par (objetos de par creados por la plantilla de clase de par).

par par clave-valor (pair<const K, T>): el primer elemento en el par clave-valor es clave (clave), que se utiliza para buscar, y el segundo elemento es valor (valor).

Usando cada par clave-valor almacenado en el contenedor del mapa, el valor de la clave no se puede repetir ni modificar.

Al usar el contenedor de mapas para almacenar varios pares clave-valor, de forma predeterminada, todos los pares clave-valor se ordenarán automáticamente en orden ascendente según el tamaño de la clave de cada par clave-valor.

2. Construcción y asignación de contenedores de mapas

Construcción por defecto: map<T1,T2> m;

Al crear un contenedor de mapas con una construcción predeterminada, también se puede inicializar

Copiar construcción: map(const map &m);

Al llamar al constructor de copias del contenedor de mapas, se puede crear con éxito el mismo contenedor de mapas.

Constructor de movimiento: pase el objeto de mapa creado temporalmente como un parámetro al contenedor de mapa que se va a inicializar y, a continuación, llame al constructor de movimiento para crear el contenedor de mapa.

//返回临时map对象的函数
map<string,int> disMap() {
    map<string, int>tempMap{ {"C语言",1},{"STL",2} };
    return tempMap;
}
//用临时map对象做为参数调用移动构造函数创建map容器
map<string, int>newMap(disMap());
复制代码

Construcción de intervalos: tome los pares clave-valor en el área especificada en el contenedor de mapas existente, cree e inicialice un nuevo contenedor de mapas

map<string, int>oldMap{ {"C语言",10},{"STL",20} };
map<string, int>newMap(++myMap.begin(), myMap.end());
复制代码

ejemplo de código

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

void printMap(map<int, int>& m) {
	for (map<int, int>::iterator it = m.begin(); it != m.end(); it++) {
		cout << (*it).first << " " << (*it).second << endl;
	}
	cout << endl;
}
//返回临时map对象的函数
map<int, int> disMap() {
	map<int, int>tempMap{ {5,40},{4,50} };
	return tempMap;
}

void test01() {
	//默认构造
	map<int, int> m;
	map<int, int> m1{{3,10},{1,20},{2,30}};
	printMap(m1); 

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

	//赋值
	map<int, int> m4;
	m4 = m3;
	printMap(m4);

	//区间构造
	map<int, int> m5(++m3.begin(), m3.end());
	printMap(m5);

	//移动构造
	map<int, int> m6(disMap());
	printMap(m6);
}
int main() {
	test01();
	system("pause");
	return 0;
}
复制代码

在这里插入图片描述

3. Mapear el tamaño del contenedor y el intercambio

método miembro Función
vacío() Devuelve verdadero si el contenedor está vacío; de lo contrario, falso.
tamaño() Devuelve el número de pares clave-valor almacenados en el contenedor del mapa actual.
intercambio() Intercambie los pares clave-valor almacenados en dos contenedores de mapa y los dos pares clave-valor deben ser del mismo tipo.
#include<iostream>
using namespace std;
#include<map>

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> mp{{1, 10},{3, 20},{4, 30},{2, 40}};
	if (!mp.empty()) {
		cout << "容器mp不为空" << endl;
		cout << "容器的大小为:" << mp.size();
		cout << endl;
	}
	else {
		cout << "容器为空" << endl;
	}
	map<int, int> m1{{1, 1},{3, 2},{4, 3},{2, 4}};
	cout << "交换前:" << endl;
	printMap(mp);
	printMap(m1);
	cout << "交换后: " << endl;
	mp.swap(m1);
	printMap(mp);
	printMap(m1);
}
int main() {
	test01();
	system("pause");
	return 0;
}
复制代码

在这里插入图片描述

4. Agregar y eliminar contenedores de mapas

método miembro Función
insertar (elemento) Agregue pares clave-valor al contenedor.
claro() Borre todos los pares clave-valor en el contenedor del mapa y el tamaño () del contenedor del mapa es 0.
borrar (pos) Elimine el par clave-valor en la posición pos y devuelva un iterador al siguiente elemento.
borrar (comenzar, terminar) Elimine los pares clave-valor en el rango [beg,end] y devuelva un iterador al siguiente elemento.
borrar (clave) Elimine el par clave-valor de la clave especificada en el contenedor.

Uso del operador []

Use el operador [ ] para obtener el valor correspondiente a la clave especificada, y también modifique el valor correspondiente a la clave especificada;

如果修改时 map 容器内部没有存储以 [ ] 运算符内指定数据为键的键值对,则使用 [ ] 运算符会向当前 map 容器中添加一个新的键值对。

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

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

	map<string, int> m1{ {"STL",5} };
	cout <<  "获取指定键对应的值:" << m1["STL"] << endl;

	//向 map 容器添加新键值对
	m1["Python"] = 6;
	//修改 map 容器中指定键对应的值,如果指定键不存在则会执行添加操作
	m1["STL"] = 50;
	printMap(m1);

}
int main() {
	test01();
	system("pause");
	return 0;
}
复制代码

在这里插入图片描述

4.1、insert插入数据的四种方式

当使用 insert() 方法向 map 容器的指定位置插入新键值对时,其底层会先将新键值对插入到容器的指定位置,如果其破坏了 map 容器的有序性,该容器会对新键值对的位置进行调整。

  • 如果插入成功,insert() 方法会返回一个指向 map 容器中已插入键值对的迭代器;
  • 如果插入失败,insert() 方法同样会返回一个迭代器,该迭代器指向 map 容器中和 val 具有相同键的那个键值对。

1、不指定位置,直接添加键值对

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

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

void test01() {

	map<string, int> m;

	//创建一个pair键值对
	pair<string, int> pair1 = { "STL",20 };
	//添加pair到map中
	m.insert(pair1);
	m.insert({ "C",40 });

	//调用 pair 类模板的构造函数添加
	m.insert(pair<string, int>("JAVA", 10));
	//调用 make_pair() 函数添加
	m.insert(make_pair("python", 20));
	printMap(m);
}
int main() {
	test01();
	system("pause");
	return 0;
}
复制代码

在这里插入图片描述

2、向指定位置插入键值对

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

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

void test01() {

	map<string, int> m;

	//创建一个pair键值对
	pair<string, int> pair1 = { "STL",20 };
	//添加pair到map中
	m.insert(m.begin(),pair1);

	//调用 pair 类模板的构造函数添加
	m.insert(m.begin(),pair<string, int>("JAVA", 10));
	//调用 make_pair() 函数添加
	m.insert(m.end(), make_pair("python", 20));
	printMap(m);
}
int main() {
	test01();
	system("pause");
	return 0;
}
复制代码

在这里插入图片描述

3、向 map 容器中插入其它 map 容器区间内的所有键值对

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

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

void test01() {

    map<string, int> m;
	map<string, int> m1{ {"STL教程",20},{"C语言教程",50},{"Java教程",30} };
	printMap(m1);
    //将<first,last>区域内的键值对插入到 copymap 中
	m.insert(++m1.begin(), m1.end());
	printMap(m);
}
int main() {
	test01();
	system("pause");
	return 0;
}
复制代码

在这里插入图片描述

4、一次向 map 容器中插入多个键值对

map<string, int> m;
m.insert({ {"STL",1},{ "C语言",2},{ "Java",30} });
复制代码

4.2、删除键值对

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

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

void test01() {

    map<string, int> m;
	m.insert({ { "STL",1}, {"C语言",2}, {"Java",30}, {"MySQL",5}, {"Docker",70}, {"Redis",3} });
	printMap(m);

	//清除
	m.erase(++m.begin());
	printMap(m);
    
    //清除区间
	m.erase(++m.begin(), --m.end());
	printMap(m);

    //按照key删除
	m.erase("C语言");
	printMap(m);

    //清除全部
	m.clear();
	printMap(m);

}
int main() {
	test01();
	system("pause");
	return 0;
}
复制代码

在这里插入图片描述

5、map容器查找和统计

成员方法 功能
find(key) 在 map 容器中查找键为 key 的键值对,如果成功找到,则返回指向该键值对的双向迭代器;反之,则返回和 end() 方法一样的迭代器。
count(key) 在当前 map 容器中,查找键为 key 的键值对的个数并返回。由于 map 容器中各键值对的键的值是唯一的,因此该函数的返回值最大为 1。
#include<iostream>
using namespace std;
#include<map>

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> mp;
	mp.insert({ {1,10},{3, 20},{4, 30} });

	map<int, int>::iterator it = mp.find(4);
	if (it != mp.end()) {
		cout << "查到了元素的key值为: " << (*it).first << " 元素的value值为: " << (*it).second << endl;
	}
	else {
		cout << "没有查到这个key的对组" << endl;
	}
	it = mp.find(5);
	if (it != mp.end()) {
		cout << "查到了元素的key值为 " << (*it).first << " 元素的value值为: " << (*it).second << endl;
	}
	else {
		cout << "没有查到这个key的对组" << endl;
	}
	//map的统计值只有0和1
	int num1 = mp.count(1);
	int num2 = mp.count(6);
	cout << num1 << "  " << num2 << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
复制代码

在这里插入图片描述

6、map容器排序

map容器默认是升序排序的,利用仿函数可以改变map的排序规则

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

class MyCompare {
public:
	bool operator()(int v1, int v2) const {
		return v1 > v2;
	}
};
//map降序排序
void printMap(map<int, int, MyCompare>& m) {
	for (map<int, int, MyCompare>::iterator it = m.begin(); it != m.end(); it++) {
		cout << "key=" << (*it).first << " value=" << (*it).second << endl;
	}
	cout << endl;
}
void test01() {
	map<int, int, MyCompare> mp;
	mp.insert({ {1,10},{3, 20},{4, 30} });
	printMap(mp);
}
int main() {
	test01();
	system("pause");
	return 0;
}
复制代码

在这里插入图片描述

Supongo que te gusta

Origin juejin.im/post/7222257177187631160
Recomendado
Clasificación