Classe de contêiner STL

STL

1. Introdução ao STL

1.1 Iteradores

1.1.1 Ponteiros nativos também são iteradores

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
void test01() {
	int arr[5] = { 1,2,3,4,5 };
	int* p = arr;
	for (int i = 0; i < 5; i++) {
		cout << arr[i] << endl;
		cout << *(p+i) << endl;
	}
};
int main() {
	test01();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501182726266

1.1.2 Iteração de loop

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void print(int i) {
    
    

	cout <<i << endl;
}
void test02() {
    
    
	vector<int >v;
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);
	vector<int>::iterator itbegin = v.begin();
	vector<int>::iterator itend = v.end();
	while (itbegin != itend) {
    
    
		cout << *itbegin << endl;
		itbegin++;
	}
	for (vector<int>::iterator i = itbegin; i!=v.end();i++) {
    
    
		cout << *i << endl;
	}
	for_each(v.begin(), v.end(), print);
}


int main() {
    
    
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501192746580

1.1.3 Estrutura de dados personalizada

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Person {
public:
	Person(string name,int age) {
		this->name = name;
		this->age = age;
	}
	string name;
	int age;
};
void test03() {
	vector<Person> v;
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);
	Person p5("eee", 50);
	Person p6("fff", 60);
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);
	v.push_back(p5);
	v.push_back(p6);
	for (vector<Person>::iterator it = v.begin(); it!=v.end(); it++) {
		cout << (*it).name<< endl;
	}
}
int main() {
	test03();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501195143536

Recipiente de string 1.2

1.2.1 inicialização de string

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test01() {
	string str;// 初始化对象
	string str2(str); // 用另外一个对象初始化
	string str3 = "abc"; // 把值赋值给当前字符串
	string str4(10, 'q'); // 用n个字符赋值给当前字符串
	cout << "str3= " << str3 << endl;
	cout << "str4= " << str4 << endl;
}

int main() {
	test01();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501201634698

1.2.2 Atribuição de strings

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test02() {
	string str;
	str = "abc";

	str.assign("abcde", 3);
	cout << str << endl;

	string str2;
	str2.assign(str); //字符串赋值
	cout << str2 << endl;
	str2.assign(str, 0, 2); // 将s从start开始n个字符赋值给字符串
	cout << str2 << endl;

}

int main() {
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501201942683

1.2.3 no valor do cheque

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test03() {
	string str="hello world!";
	for (int i = 0; i < str.size(); i++) {
		cout << str[i] << endl;
	}
	// [] 和at 区别,[] 访问越界直接挂掉,at访问越界,抛出out_of_range 异常
	try {
		cout << str.at(100) << endl;
	}
	catch (out_of_range& e) {
		cout << e.what() << endl;
	}
	catch (...) {
		cout << "异常捕获"<<endl;
	}

}

int main() {
	test03();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501203038084

1.2.4 CRUD

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test04() {
	// 字符串拼接
	string  str1 = "我";
	string str2 = "爱天安门";
	cout <<"1:" << str1 + str2 << endl;
	cout <<"2:" << str1.append(str2) << endl;

	string str = "abcdefgde";
	int pos = str.find("de");

	if (pos == -1) {
		cout << "未找到字符串" << endl;
	}
	else
	{
		cout << "找到了字符串,位置为:" << pos << endl;
	}
	str.replace(1, 3, "11111");// 替换从pos开始n个字符的字符串为str
	cout << str << endl;
}

int main() {
	test04();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501204621438

1.2.5 Comparação de Strings

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test05() {
	string str1 = "abcde";
	string str2 = "abcdef";
	if (str1.compare(str2) == 0) {
		cout << "str1==str2" << endl;
	}
	else if (str1.compare(str2) > 0) {
		cout << "str1>str2" << endl;
	}
	else
	{
		cout << "str1<str2" << endl;

	}
}

int main() {
	test05();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501205006747

1.2.6 Índice de String

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test06() {
	string email = "[email protected]";
	int pos = email.find("@");
	// [start:end]
	string userName = email.substr(0, pos);
	cout << userName << endl;
}

int main() {
	test06();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501205256320

1.2.7 Analisando Strings

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test07() {
	string str = "www.baidu.com";
	vector<string> v;
	int start = 0;
	int pos = -1;
	while (true) {
		pos = str.find(".", start);
		if (pos == -1) {
			string tempStr = str.substr(start, str.size() - start);
			v.push_back(tempStr);
			break;
		}
		string tempStr = str.substr(start, pos - start);
		v.push_back(tempStr);
		start = pos + 1;
	}
	for (vector<string>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << endl;
	}
		
}

int main() {
	test07();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501213945866

1.2.8 Inserção e exclusão

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test08() {
	string str = "hello";
	str.insert(1, "111");

	cout << str << endl;

	str.erase(1, 3);// 从pos开始的n个字符
	cout << str << endl;

}

int main() {
	test08();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501214139969

1.2.9 Conversão entre char e string

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test09() {
	const char* str = "abcd";
	// 转str
	string s(str);

	//str 转const
	const char* str2 = s.c_str();
	// const char* 可以隐式转换string,反之不可

}
int main() {
	test09();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501214428988

1.2.10 Conversão de strings

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test10() {
	string s = "abcdefg";
	char& a = s[2];
	char& b = s[3];

	a = '1';
	b = '2';
	cout << s << endl;
	cout << (int*)s.c_str() <<endl;
	s = "ppppppppppppppp";

	cout << s << endl;
	cout << (int*)s.c_str() << endl;


}
int main() {
	test10();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501214651331

1.3. contêiner de vetor

1.3.1 capacidade

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void test01() {
	vector<int> v;
	for (int i = 0; i < 10; i++){
		v.push_back(i);
		cout << v.capacity() << endl;  // v.capacity()容器的容量
	}
}

int main() {
	test01();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501225522551

1.3.2 Atribuição

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;

void printVector(vector<int>& v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void test02() {
	vector<int>v1;
	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(30);
	v1.push_back(40);
	v1.push_back(50);
	//vector& operator=(const vector & vec);//重载等号操作符
	//assign(beg, end);//将[beg, end)区间中的数据拷贝赋值给本身。
	//assign(n, elem);//将n个elem拷贝赋值给本身。
	//vector& operator=(const vector & vec);//重载等号操作符
	vector<int>v2(v1.begin(), v1.end());
	printVector(v2);
	vector<int>v3;
	v3.assign(v1.begin(), v1.end());
	printVector(v3);
	vector<int>v4(10, 100);
	printVector(v4);
	cout << "v3和v4互换后:" << endl;
	v3.swap(v4);
	printVector(v3);
	printVector(v4);
}

int main() {
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501230444646

1.3.3 Julgamento e operação de status

  • size(); //retorna o número de elementos no contêiner
  • vazio(); // Determina se o contêiner está vazio
  • resize(int num);//Reespecifique o comprimento do contêiner para num. Se o contêiner ficar mais longo, preencha a nova posição com o valor padrão. Se o contêiner ficar mais curto, os elementos da extremidade que excedem o comprimento do contêiner serão removidos.
  • resize(int num, elem);//Reespecifique o comprimento do contêiner para num. Se o contêiner ficar mais longo, preencha a nova posição com o valor do elemento. Se o contêiner ficar mais curto, os elementos da extremidade que excedem o comprimento do contêiner serão removidos.
  • capacidade();//capacidade do contêiner
  • reserve(int len);//O contêiner reserva os elementos len em comprimento, a posição reservada não é inicializada e os elementos ficam inacessíveis.
  • at(int idx); //Retorna os dados apontados pelo índice idx. Se idx estiver fora dos limites, uma exceção out_of_range será lançada.
  • operador[];//Retorna os dados apontados pelo índice idx. Quando fora dos limites, um erro será relatado diretamente durante a operação.
  • front(); //Retorna o primeiro elemento de dados no contêiner
  • back(); //Retorna o último elemento de dados no contêiner
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void printVector(vector<int>& v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void test03()
{
	vector<int>v1;
	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(30);
	v1.push_back(40);
	v1.push_back(50);

	if (v1.empty())
	{
		cout << "v1为空" << endl;
	}
	else
	{
		cout << "v1不为空 ,大小为: " << v1.size() << endl;
	}

	v1.resize(10, 100); //第二个参数代表默认填充值

	printVector(v1);

	v1.resize(3);

	printVector(v1);

	cout << "v1的front = " << v1.front() << endl;
	cout << "v1的back  = " << v1.back() << endl;

}

int main() {
	test03();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501231011665

1.3.4 Inserção e exclusão

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void printVector(vector<int>& v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void test04()
{
	vector<int>v;
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);

	v.insert(v.begin(), 100);

	printVector(v);

	v.push_back(1000);

	printVector(v);

	v.pop_back();

	printVector(v);


	v.erase(v.begin());
	printVector(v);

	//v.erase(v.begin(), v.end()); 等价于  v.clear();
	v.clear();
	//v.erase(v.begin(), v.end());
	printVector(v);

}



int main() {
	test04();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230501231145772

1.4 e

1.4.1 Construtor

  • deque deqT; //Formulário de construção padrão
  • deque(beg, end);//O construtor copia os elementos no intervalo [beg, end) para si mesmo.
  • deque(n, elem);//O construtor copia n elem para si mesmo.
  • deque(const deque &deq);//Copia construtor.
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<deque>
#include<algorithm>
#include<string>
using namespace std;
void printDeque(const deque<int>& d)
{
	//iterator普通迭代器
	//reverse_iterator 反转迭代器
	//const_iterator  只读迭代器

	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
		//*it = 1000;
		cout << *it << " ";
	}
	cout << endl;
}
void test01()
{
	deque<int>d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	d.push_back(40);
	deque<int>d2;
	d2 = d;
	printDeque(d2);

	if (d2.empty())
	{
		cout << "d2为空" << endl;
	}
	else
	{
		cout << "d2不为空 size = " << d2.size() << endl;
	}
}
void test02() {
	deque<int>d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	d.push_back(100);
	d.push_back(200);
	d.push_back(300);
	printDeque(d);
	d.pop_back(); // 尾删
	d.pop_front(); // 头删
	printDeque(d);
	cout << "第一个元素为:" << d.front() << endl;
	cout << "最后一个元素为:" << d.back() << endl;
	
}
int main() {
	test01();
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230502103418754

1.4.2 Operação de atribuição

  • atribua(beg, end);//Copia e atribui os dados no intervalo [beg, end) para si mesmo.
  • atribua(n, elem);//Atribua n cópias do elemento a si mesmo.
  • deque& operator=(const deque &deq); //Sobrecarregando o operador de sinal de igual
  • swap(deq);// Troca deq com seus próprios elementos
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<deque>
#include<algorithm>
#include<string>
using namespace std;
void printDeque(const deque<int>& d)
{
	//iterator普通迭代器
	//reverse_iterator 反转迭代器
	//const_iterator  只读迭代器

	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
		//*it = 1000;
		cout << *it << " ";
	}
	cout << endl;
}
void test01()
{
	deque<int>d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	d.push_back(40);
	deque<int>d2;
	d2 = d;
	printDeque(d2);

	if (d2.empty())
	{
		cout << "d2为空" << endl;
	}
	else
	{
		cout << "d2不为空 size = " << d2.size() << endl;
	}
}
void test02() {
	deque<int>d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	d.push_back(100);
	d.push_back(200);
	d.push_back(300);
	printDeque(d);
	d.pop_back(); // 尾删
	d.pop_front(); // 头删
	printDeque(d);
	cout << "第一个元素为:" << d.front() << endl;
	cout << "最后一个元素为:" << d.back() << endl;
	
}
void test03(){
	deque<int>d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	d.push_back(100);
	d.push_back(200);
	d.push_back(300);
	d.insert(++d.begin(), 2, 1000);
	printDeque(d);
	d.erase(++d.begin());
	d.erase(++d.begin());
	deque<int>::iterator it1 = d.begin();
	it1 = it1 + 1;
	deque<int>::iterator it2 = d.begin();
	it2 = it2 + 3;
	d.erase(it1, it2);
	printDeque(d);
	d.clear();
	printDeque(d);
}
bool myComare(int v1, int v2) {
	return v1 < v2;
}
int main() {
	// test01();
	// test02();
	test03();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230502103936561

1.4.3 Operação de tamanho

  • deque.size();//Retorna o número de elementos no contêiner
  • deque.empty();//Determina se o contêiner está vazio
  • deque.resize(num);//Especifique novamente o comprimento do contêiner para num. Se o contêiner ficar mais longo, preencha a nova posição com o valor padrão. Se o contêiner ficar mais curto, os elementos da extremidade que excedem o comprimento do contêiner serão removidos.
  • deque.resize(num, elem); //Especifique novamente o comprimento do contêiner para num. Se o contêiner ficar mais longo, a nova posição será preenchida com o valor do elemento. Se o contêiner ficar mais curto, os elementos no final que excedem o comprimento do contêiner será excluído.
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<deque>
#include<algorithm>
#include<string>
using namespace std;
void printDeque(const deque<int>& d)
{
	//iterator普通迭代器
	//reverse_iterator 反转迭代器
	//const_iterator  只读迭代器

	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
		//*it = 1000;
		cout << *it << " ";
	}
	cout << endl;
}
void test01()
{
	deque<int>d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	d.push_back(40);
	deque<int>d2;
	d2 = d;
	printDeque(d2);

	if (d2.empty())
	{
		cout << "d2为空" << endl;
	}
	else
	{
		cout << "d2不为空 size = " << d2.size() << endl;
	}
}
void test02() {
	deque<int>d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	d.push_back(100);
	d.push_back(200);
	d.push_back(300);
	printDeque(d);
	d.pop_back(); // 尾删
	d.pop_front(); // 头删
	printDeque(d);
	cout << "第一个元素为:" << d.front() << endl;
	cout << "最后一个元素为:" << d.back() << endl;
	
}
void test03(){
	deque<int>d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	d.push_back(100);
	d.push_back(200);
	d.push_back(300);
	d.insert(++d.begin(), 2, 1000);
	printDeque(d);
	d.erase(++d.begin());
	d.erase(++d.begin());
	deque<int>::iterator it1 = d.begin();
	it1 = it1 + 1;
	deque<int>::iterator it2 = d.begin();
	it2 = it2 + 3;
	d.erase(it1, it2);
	printDeque(d);
	d.clear();
	printDeque(d);
}
bool myComare(int v1, int v2) {
	return v1 < v2;
}
void test04() {
	deque<int>d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	d.push_front(100);
	d.push_front(200);
	d.push_front(300);
	// 默认排序从小到大
	//sort(d.begin(), d.end());
	sort(d.begin(), d.end(), myComare);
	printDeque(d);
}
int main() {
	// test01();
	// test02();
	// test03();
	test04();
	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230502104600016

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<deque>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
class Player
{
public:
	Player(string name, int score) {
		this->m_Name = name;
		this->m_Score = score;
	};
	string m_Name; // 姓名
	int m_Score; // 平均分
};
void createPlayer(vector<Player>& v) {
	string nameSeed = "ABCDE";
	for (int i = 0; i < 5; i++) {
		string name = "选手";
		name += nameSeed[i];
		int score = 0;
		Player player(name, score);
		v.push_back(player);
	}
};
void setScore(vector<Player>& v) {
	for (vector<Player>::iterator it = v.begin(); it != v.end(); it++) {
		deque<int> d;
		for (int i = 0; i < 10; i++) {
			int score = rand() % 41 + 60;
			d.push_back(score);
		}
		sort(d.begin(), d.end());
		
		d.pop_back();
		d.pop_front();

		int sum = 0;
		for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++) {
			sum += *dit;
		}
		int avg = sum / d.size();
		it->m_Score = avg;
	}
}
void showScore(vector<Player>&v){
	for (vector<Player>::iterator it = v.begin(); it != v.end(); it++) {
		cout << "姓名:" << (*it).m_Name << "平均分数:" << it->m_Score << endl;
	}

}
int main() {
	srand((unsigned int)time(NULL));
	vector<Player> v;
	createPlayer(v);

	setScore(v);

	showScore(v);
	
	

	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230502112016665

1.5 Empilhar contêiner

  • stack& operator=(const stack &stk);//Sobrecarregando o operador de sinal de igual
  • push(elem); //Adiciona elementos ao topo da pilha
  • pop(); //Remove o primeiro elemento do topo da pilha
  • top(); //Retorna o elemento superior da pilha
  • vazio(); // Determina se a pilha está vazia
  • size(); //Retorna o tamanho da pilha
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include <stack>

void test01()
{
	stack<int>S;
	//入栈
	S.push(10);
	S.push(20);
	S.push(30);
	S.push(40);

	cout << "size  = " << S.size() << endl;

	while (!S.empty())
	{
		//访问栈顶元素
		cout << S.top() << endl;
		//出栈
		S.pop();
	}
	cout << "size  = " << S.size() << endl;

}


int main() {

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230502112311130

1.6 fila

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include <queue>
#include <string>
class Person
{
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}
	string m_Name;
	int m_Age;
};

void test01()
{
	queue<Person> Q; //队列容器

	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);


	//入队
	Q.push(p1);
	Q.push(p2);
	Q.push(p3);
	Q.push(p4);

	cout << "size = " << Q.size() << endl;

	while ( !Q.empty())
	{
		cout << "队头元素--- 姓名:  " << Q.front().m_Name << " 年龄: " << Q.front().m_Age << endl;
		cout << "队尾元素--- 姓名:  " << Q.back().m_Name << " 年龄: " << Q.back().m_Age << endl;

		//出队
		Q.pop();
	}

	cout << "size = " << Q.size() << endl;

}

int main(){

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

imagem-20230502112530044

1.7 lista de contêiner

1.7.1 Construtor

  • list lstT;//list é implementado usando uma classe de modelo, e a forma de construção padrão do objeto é:
  • list(beg, end);//O construtor copia os elementos no intervalo [beg, end) para si mesmo.
  • list(n,elem);//O construtor copia n elementos para si mesmo.
  • list(const list &lst);//Copia construtor.
  • push_back(elem);//Adiciona um elemento ao final do contêiner pop_back();//Exclui o último elemento do contêiner
  • push_front(elem); //Insere um elemento no início do contêiner
  • pop_front();//Remove o primeiro elemento do início do contêiner
  • insert(pos,elem);//Insere uma cópia do elemento elem na posição pos e retorna a posição dos novos dados.
  • insert(pos,n,elem);//Insere dados de n elem na posição pos, sem valor de retorno.
  • insert(pos,beg,end);//Insere os dados no intervalo [beg,end) na posição pos, sem valor de retorno.
  • clear(); //Remove todos os dados do contêiner
  • erase(beg,end);//Exclui os dados no intervalo [beg,end) e retorna a posição dos próximos dados.
  • erase(pos);//Exclui os dados na posição pos e retorna a posição dos próximos dados.
  • remove(elem);//Exclui todos os elementos do contêiner que correspondem ao valor do elemento.
list<T> lstT;//list采用采用模板类实现,对象的默认构造形式:
list(beg,end);//构造函数将[beg, end)区间中的元素拷贝给本身。
list(n,elem);//构造函数将n个elem拷贝给本身。
list(const list &lst);//拷贝构造函数。

1.7.2 Operações de inserção e exclusão de elementos de dados

push_back(elem);//在容器尾部加入一个元素
pop_back();//删除容器中最后一个元素
push_front(elem);//在容器开头插入一个元素
pop_front();//从容器开头移除第一个元素
insert(pos,elem);//在pos位置插elem元素的拷贝,返回新数据的位置。
insert(pos,n,elem);//在pos位置插入n个elem数据,无返回值。
insert(pos,beg,end);//在pos位置插入[beg,end)区间的数据,无返回值。
clear();//移除容器的所有数据
erase(beg,end);//删除[beg,end)区间的数据,返回下一个数据的位置。
erase(pos);//删除pos位置的数据,返回下一个数据的位置。
remove(elem);//删除容器中所有与elem值匹配的元素。

1.7.3 Operação de tamanho de lista

size();//返回容器中元素的个数
empty();//判断容器是否为空
resize(num);//重新指定容器的长度为num,
若容器变长,则以默认值填充新位置。
如果容器变短,则末尾超出容器长度的元素被删除。
resize(num, elem);//重新指定容器的长度为num,
若容器变长,则以elem值填充新位置。
如果容器变短,则末尾超出容器长度的元素被删除。

1.7.4 Acesso aos dados da lista

front();//返回第一个元素。
back();//返回最后一个元素。

1.7.5 Classificação reversa de lista

reverse();//反转链表,比如lst包含1,3,5元素,运行此方法后,lst就包含5,3,1元素。
sort(); //list排序

1,8 conjunto/multiconjunto

  • As características do Set são. Todos os elementos são classificados automaticamente com base no valor-chave do elemento. Ao contrário do mapa, os elementos de Set podem ter valores reais e valores-chave. Os elementos de Set são valores-chave e valores reais. Set não permite que dois elementos tenham o mesmo valor de chave.
  • As características e utilização do multiset são exatamente as mesmas do set. A única diferença é que ele permite a duplicação de valores-chave. A implementação subjacente de set e multiset é uma árvore vermelha e preta, que é um tipo de árvore binária balanceada.

1.8.1 Construtor

set<T> st;//set默认构造函数:
mulitset<T> mst; //multiset默认构造函数: 
set(const set &st);//拷贝构造函数

1.8.2 Operação de atribuição

set& operator=(const set &st);//重载等号操作符
swap(st);//交换两个集合容器

1.8.3 Operação de definição de tamanho

size();//返回容器中元素的数目
empty();//判断容器是否为空

1.8.4 Operações de inserção e exclusão

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

1.8.5 Operação de pesquisa

find(key);//查找键key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();
count(key);//查找键key的元素个数
lower_bound(keyElem);//返回第一个key>=keyElem元素的迭代器。
upper_bound(keyElem);//返回第一个key>keyElem元素的迭代器。
equal_range(keyElem);//返回容器中key与keyElem相等的上下限的两个迭代器。

1.9 mapa/contêiner multimapa

1.9.1 Conceitos básicos de mapa/multimapa

A característica do Map é que todos os elementos são classificados automaticamente de acordo com o valor-chave do elemento. Todos os elementos do mapa são pares, com valores reais e valores-chave. O primeiro elemento de um par é considerado um valor-chave e o segundo elemento é considerado um valor real. O mapa não permite que dois elementos tenham o mesmo valor chave.

O valor-chave do mapa está relacionado às regras de organização dos elementos do mapa. Qualquer alteração no valor-chave do mapa prejudicará seriamente a organização do mapa. Se quiser modificar o valor real de um elemento, você pode.

Mapa e lista têm algumas das mesmas propriedades. Ao adicionar ou excluir seus elementos de contêiner, todos os iteradores antes da operação ainda são válidos após a conclusão da operação. É claro que o iterador do elemento excluído deve ser uma exceção.

As operações multimapa e mapa são semelhantes, a única diferença é que os valores-chave multimapa podem ser repetidos.

Tanto o mapa quanto o multimapa usam árvores vermelho-pretas como mecanismo de implementação subjacente.

1.9.2 Construtor

map<T1, T2> mapTT;//map默认构造函数: 
map(const map &mp);//拷贝构造函数

1.9.3 Atribuição

map& operator=(const map &mp);//重载等号操作符
swap(mp);//交换两个集合容器

1.9.4 Operação de tamanho do mapa

size();//返回容器中元素的数目
empty();//判断容器是否为空

1.9.5 Operação de inserção de elemento

map.insert(...); //往容器插入元素,返回pair<iterator,bool>
map<int, string> mapStu;
// 第一种 通过pair的方式插入对象
mapStu.insert(pair<int, string>(3, "小张"));
// 第二种 通过pair的方式插入对象
mapStu.inset(make_pair(-1, "校长"));
// 第三种 通过value_type的方式插入对象
mapStu.insert(map<int, string>::value_type(1, "小李"));
// 第四种 通过数组的方式插入值
mapStu[3] = "小刘";
mapStu[5] = "小王";

1.9.6 operação de exclusão de mapa

clear();//删除所有元素
erase(pos);//删除pos迭代器所指的元素,返回下一个元素的迭代器。
erase(beg,end);//删除区间[beg,end)的所有元素 ,返回下一个元素的迭代器。
erase(keyElem);//删除容器中key为keyElem的对组。

1.9.7 operação de pesquisa de mapa

find(key);//查找键key是否存在,若存在,返回该键的元素的迭代器;/若不存在,返回map.end();
count(keyElem);//返回容器中key为keyElem的对组个数。对map来说,要么是0,要么是1。对multimap来说,值可能大于1。
lower_bound(keyElem);//返回第一个key>=keyElem元素的迭代器。
upper_bound(keyElem);//返回第一个key>keyElem元素的迭代器。
equal_range(keyElem);//返回容器中key与keyElem相等的上下限的两个迭代器。

Acho que você gosta

Origin blog.csdn.net/weixin_42917352/article/details/130468454
Recomendado
Clasificación