Notas de estudo de C++ Contêineres deque de vetor de 24 strings comumente usados em contêineres STL

1 recipiente de corda

1.0 Conceito básico de string

Essência :

  • string é uma string no estilo C++, que é essencialmente uma classe encapsulada

A diferença entre string e char* :

  • char* é um ponteiro
  • string é uma classe que encapsula char* dentro da classe e gerencia essa string, que é um container do tipo char*.

Recursos :
A classe string encapsula internamente muitos métodos de membro
, como: localizar localizar, copiar copiar, excluir excluir, substituir substituir, inserir inserir
string para gerenciar a memória alocada por char*, não se preocupe em copiar fora dos limites e valor fora de limites, etc., e a classe é responsável por isso.


1.1 construtor de strings

Protótipo do construtor (4 sobrecargas de função):

  • string();Crie uma string vazia, por exemplo: string str;.
    string(const char* s);Inicializado com a string s.

  • string(const string& str);Use um objeto string para inicializar outro objeto string

  • string(int n, char c);Inicializar com n caracteres c

Exemplo :

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

void test1_01()
{
    
    
	string s1;  //默认构造
	cout << "s1 = " << s1 << endl;

	const char* str = "hello world";
	string s2(str);     //使用C++字符串初始化
	cout << "s2 = " << s2 << endl;

	string s3(s2);     //拷贝构造
	cout << "s3 = " << s3 << endl;

	string s4(3, 'h');
	cout << "s4 = " << s4 << endl;

}
int main()
{
    
    
	test1_01();
	system("pause");
	return 0;
}

1.2 operação de atribuição de string

Protótipo de função para atribuição (3 sobrecargas de operador, 4 sobrecargas de função):

string& operator=(const char* s);		//char*类型字符串赋值给当前的字符串
string& operator=(const string& s);		//把字符串s赋给当前的字符串
string& operator=(char C);				//字符赋值给当前的字符串
string& assign(const char* s);			//把字符串s赋给当前的字符串
string& assign(const char* s, int n);   //把字符串s的前n个字符赋给 当前的字符串
string& assign(const string& s);		//把字符串s赋给当前字符串
string& assign(int n, char C);			//用n个字符c赋给当前字符串

Exemplo:

#include<iostream>
using namespace std;
#include<string>
void test2_01()
{
    
    
	string str1;
	str1 = "hello world";  //string& operator=(const char* s);
	cout << "str1 = " << str1 << endl;

	string str2;
	str2 = str1;		  //string& operator=(const string& s);
	cout << "str2 = " << str2 << endl;

	string str3;
	str3 = 'c';			 //string& operator=(char c);	
	cout << "str3 = " << str3 << endl;

	string str4;
	str4.assign("hello C++");	 //string& assign(const char* s);	
	cout << "str4 = " << str4 << endl;

	string str5;
	str5.assign("hello C++", 5);	 //string& assign(const char* s, int n);	
	cout << "str5 = " << str5 << endl;

	string str6;
	str6.assign(str5);	 //string& assign(const string& s);		
	cout << "str6 = " << str6 << endl;

	string str7;
	str7.assign(5,'c');	 //string& assign(int n, char c);		
	cout << "str7 = " << str7 << endl;
}

int main()
{
    
    
	test2_01();
	system("pause");
	return 0;
}

1.3 emenda de cordas

Protótipo de função emendada (3 sobrecargas de operador, 4 sobrecargas de função):

string& operator+=(const char* str);				//重载+=操作符
string& operator+=(const char C);					//重载+=操作符
string& operator+=(const string& str);				//重载+=操作符
string& append(const char* s);						//把字符串s连接到当前字符串结尾
string& append(const char* S,int n);			    //把字符串s的前n个字符连接到当前字符串结尾
string& append(const string& s);					//同operator+=(const string& str)
string & append(const string & s, int pos, int n);  //字符串s中从pos开始的n个字符连接到字符串结尾

Exemplo:

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

void test3_01(){
    
    
	string str1 = "我";
	str1 += "爱玩游戏";				//string& operator+=(const char* str);
	cout << "str1 = " << str1 << endl;			

	str1 += ':';						//string& operator+=(const char C);
	cout << "str1 = " << str1 << endl;

	string str2 = "LOL,DNF";
	str1 += str2;						//string& operator+=(const string & str);
	cout << "str2 = " << str2 << endl;

	string str3 = "I";
	str3.append(" love ");				//string& append(const char* s)
	cout << "str3 = " << str3 << endl;

	str3.append(" game , study ", 6);	//string& append(const char* S,int n);
	cout << "str3 = " << str3 << endl;

	string str4 = str3;
	str3.append(str2);					//string& append(const string& s);	
	cout << "str3 = " << str3 << endl;

	str4.append(str2, 4, 6);			//string& append(const string & s, int pos, int n);
	cout << "str4 = " << str4 << endl;
}

int main(){
    
    
	test3_01();
	system("pause");
	return 0;
}

1.4 string localizar e substituir

Protótipo de função:

int find(const string& str, int pos = 0) const;			//查找str第一次出现位置,从pos开始查找
int find(const char* s, int pos = 0) const;				//查找s第一次出现位置从pos开始查找
int find(const char* s, int pos, int n) const;			//从pos位置查找s的前n个字符第一-次位置
int find(const char C,int pos = 0) const;				//查找字符c第一次出现位置
int rfind(const string& str, int pos = npos) const;		//查找str最后一次位 置从pos开始查找
int rfind(const char* s,int pos = npos) const;			//查找s最后一-次出现位置,从pos开始查找
int rfind(const char* s,int pos, int n) const;			//从pos查找s的前n个字符最后一-次位置
int rfind(const char C,int pos = 0) const;				//查找字符c最后一次出现位置
string& replace(int pos, int n, const string& str);     //替换从pos开始n个字符为字符串str
string& replace(int pos, int n, const char* s);			//替换从pos开始的n个字符为字符串s

Exemplo:

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

//int find(const string& str, int pos = 0) const;			//查找str第一次出现位置,从pos开始查找
//int find(const char* s, int pos = 0) const;				//查找s第一次出现位置从pos开始查找
//int find(const char* s, int pos, int n) const;			//从pos位置查找s的前n个字符第一-次位置
//int find(const char C,int pos = 0) const;				//查找字符c第一次出现位置
//int rfind(const string& str, int pos = npos) const;		//查找str最后一次位 置从pos开始查找
//int rfind(const char* s,int pos = npos) const;			//查找s最后一-次出现位置,从pos开始查找
//int rfind(const char* s,int pos, int n) const;			//从pos查找s的前n个字符最后一-次位置
//int rfind(const char C,int pos = 0) const;				//查找字符c最后一次出现位置
//string& replace(int pos, int n, const string& str);     //替换从pos开始n个字符为字符串str
//string& replace(int pos, int n, const char* s);			//替换从pos开始的n个字符为字符串s

//查找
void test4_01() {
    
    
	string str1 = "abcdefgde";       
	int pos = str1.find("de");		//find是从左往右找
	int pos2 = str1.find("deg");
	cout << pos << endl;
	cout << pos2 << endl;

	int pos3 = str1.rfind("de");	//find是从右往左找
	int pos4 = str1.find("deg");
	cout << pos3 << endl;
	cout << pos4 << endl;
}
//替换
void test4_02() {
    
    
	string str1 = "abcdefg";
	str1.replace(1, 3, "123456");
	cout << "str1 = " << str1 << endl;
}

int main() {
    
    
	
	test4_01();
	test4_02();
	system("pause");
	return 0;
}

Resumir:

  • encontre pesquisas da esquerda para a direita e encontre pesquisas da direita para a esquerda.
  • A busca sempre retorna a posição do primeiro caractere encontrado, ou -1 se não for encontrado.
  • Ao substituir, você precisa especificar de qual posição, quantos caracteres e que tipo de string substituir (e o comprimento da string substituída pode ser diferente do número de caracteres a serem substituídos ).

Comparação de strings de 1,5 strings

Método de comparação :
a comparação de strings é baseada no código ASCII do caractere

  • = retorna 0;
  • > retorna 1;
  • < retorno -1;

Protótipo de função:

int compare(const string& s) const;  //与字符串s比 较
int compare(const char* s) const;    //与字符串s比较

Exemplo:

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

//int compare(const string& s) const;  //与字符串s比 较
//int compare(const char* s) const;    //与字符串s比较
void test5_01()
{
    
    
	string str1 = "xello";
	string str2 = "hello";

	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 main5() {
    
    
	test5_01();
	system("pasue");
	return 0;
}

1.6 acesso a caracteres de string

Existem duas maneiras de acessar um único caractere em string:

char& operator[](int n);  //通过[]方式获取字符
char& at(int n);		  //通过at方式获取字符

Exemplo:

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

//char& operator[](int n);  //通过[]方式获取字符
//char& at(int n);		  //通过at方式获取字符

void test6_01()
{
    
    
	string str = "hello";
	cout << "str = " << str << endl;

	//通过[]访问单个字符
	for (int i = 0; i < str.size(); i++)
	{
    
    
		cout << str[i] << ' ';
	}
	cout << endl;

	//通过at访问单个字符
	for (int i = 0; i < str.size(); i++)
	{
    
    
		cout << str.at(i) << ' ';
	}
	cout << endl;

	//修改
	str[0] = 'x';
	cout << "str = " << str << endl;

	str[1] = 'z';
	cout << "str = " << str << endl;
}

int main() {
    
    
	test6_01();
	system("pause");
	return 0;
}

1.7 inserção e exclusão de strings

Protótipo de função:

string& insert(int pos, const char* s);			//插入字符串
string& insert(int pos, const string& str);		//插入字符串
string& insert(int pos, int n, char C);			//在指定位置插入n个字符c
string& erase(int pos, int n = npos);			//删除从Pos开始的n个字符

Exemplo:

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

//string& insert(int pos, const char* s);			//插入字符串
//string& insert(int pos, const string& str);		//插入字符串
//string& insert(int pos, int n, char C);			//在指定位置插入n个字符c
//string& erase(int pos, int n = npos);			//删除从Pos开始的n个字符

void test7_01(){
    
    
	string str = "hello";
	str.insert(1, "111");			//string& insert(int pos, const string& str);
	cout << "str = " << str << endl;
	str.insert(0, 3, 'a');			//string& insert(int pos, int n, char C);
	cout << "str = " << str << endl;

	//删除
	str.erase(0, 3);				//string& erase(int pos, int n = npos);	
	str.erase(1, 3);
	cout << "str = " << str << endl;
}

int main(){
    
    
	test7_01();
	system("pause");
	return 0;
}

Resumo:
Inserção e exclusão são contadas a partir do índice 0.

1.8 string substring

Protótipo de função:

string substr(int pos = 0, int n = npos) const; 	//返回由pos开始的n个字符组成的字符串

Exemplo:

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

void test8_01(){
    
    
	string str = "abcdef";
	string subStr = str.substr(1, 3);
	cout << "subStr = " << subStr << endl;

	//实用操作
	string email = "[email protected]";
	//从邮件地址中获取用户名信息
	int pos = email.find('@');
	cout << pos << endl;

	string usrName = email.substr(0, pos);
	cout << "usrName = " << usrName << endl;
}
int main() {
    
    
	test8_01();
	system("pause");
	return 0;
}

2 recipientes vetoriais

2.0 Conceito básico de vetor

função :

  • A estrutura de dados do vetor é muito semelhante a uma matriz e também se torna uma matriz de terminação única .

A diferença entre vetor e array comum :

  • A diferença é que a matriz é um espaço estático e o vetor pode ser expandido dinamicamente .

Expansão dinâmica :

  • Não é para continuar o novo espaço atrás do espaço original, mas para encontrar um espaço de memória maior e, em seguida, copiar os dados originais para o novo espaço para liberar o espaço original.

insira a descrição da imagem aqui

  • O iterador do contêiner de vetor é um iterador que suporta acesso aleatório.


/

2.1 construtor de vetores

Função: criar contêiner de vetor

protótipo de função

vector<T> v;					//采用模板实现类实现,默认构造函数
vector(v.begin(), v.end());		//将v[begin,end())区间的元素拷贝给本身
vector(n, elem);				//构造函数将n个elem拷贝给本身
vector(const vector& vec);		//拷贝构造函数

Exemplo:

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

//vector<T> v;					//采用模板实现类实现,默认构造函数
//vector(v.begin(), v.end());		//将v[begin,end())区间的元素拷贝给本身
//vector(n, elem);				//构造函数将n个elem拷贝给本身
//vector(const vector& vec);		//拷贝构造函数
void printVector1(vector<int>& v){
    
    
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
    
    
		cout << *it << " ";
	}
	cout << endl;
}

void test01(){
    
    
	vector<int> v1;
	for (int i = 0; i < 10; i++)
	{
    
    
		v1.push_back(i + 1);
	}
	printVector1(v1);

	//通过区间方式进行构造
	vector<int> v2(v1.begin(), v1.end());
	printVector1(v2);

	vector<int> v3(10, 100);
	printVector1(v3);

	vector<int> v4(v3);
	printVector1(v4);
}

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


/

2.2 operação de atribuição de vetores

Protótipo de função:

vector operator=(const vector& vec);	//重载等号操作符
assign(begin, end);						//将[beg,end)区间中的数据拷贝赋值给本身
assign(n, elem);						//将n个elem拷贝赋值给本身

Exemplo:

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

//vector operator=(const vector& vec);	//重载等号操作符
//assign(begin, end);						//将[beg,end)区间中的数据拷贝赋值给本身
//assign(n, elem);						//将n个elem拷贝赋值给本身
void printVector2(vector<int>& v)
{
    
    
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
    
    
		cout << *it << " ";
	}
	cout << endl;
}

void test2_01(){
    
    
	vector<int> v1;
	for (int i = 0; i < 10; i++)
	{
    
    
		v1.push_back(i);
	}
	printVector2(v1);

	//赋值
	vector<int> v2;
	v2 = v1;
	printVector2(v2);

	//assign
	vector<int> v3;
	v3.assign(v1.begin(), v1.end());
	printVector2(v3);

	//n个elem
	vector<int> v4;
	v4.assign(10, 100);
	printVector2(v4);
}

int main(){
    
    
	test2_01();
	system("pause");
	return 0;
}

Resumo: Use = ou atribuir para atribuição.

2.3 vetor recipiente e tamanho

Protótipo de função:

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

caso:

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

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

void printVector3(vector<int> v) {
    
    
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
    
    
		cout << *it << " ";
	}
	cout << endl;
}

void test3_01(){
    
    
	vector<int> v1;
	for (int i = 0; i < 10; i++) {
    
    
		v1.push_back(i);
	}
	printVector3(v1);

	if (v1.empty()) {
    
    	//为真
		cout << "v1为空" << endl;
	}  
	else {
    
    
		cout << "v1不为空" << endl;
		cout << "v1容量为: " << v1.capacity() << endl;
		cout << "v1大小为: " << v1.size() << endl;
	}

	//重新指定大小
	v1.resize(15);
	printVector3(v1);
	cout << "reize为15后v1的容量为: " << v1.capacity() << endl;

	v1.resize(15, 100);
	printVector3(v1);
	
	//如果大小变小,会删除
	v1.resize(5);
	printVector3(v1);
	cout << "reize为5后v1的容量为: " << v1.capacity() << endl;

}

int main() {
    
    
	test3_01();
	system("pause");
	return 0;
}

2.4 inserção e exclusão de vetores

Protótipo de função:

push_back(ele);										//尾部插入元素ele
pop_back();											//删除最后一个元素
insert(const_iterator pos, ele);					//迭代器指向位置pos插入元素ele
insert(const_iterator pos, int count, ele);			//迭代器指向位置pos插入count个元素ele
erase(const_ iterator pos);							//删除迭代器指向的元素
erase(const_ iterator start, const_ iterator end);	//删除迭代器从start到end之间的元素
clear();											//删除容器中所有元素

Exemplo:

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

//push_back(ele);										//尾部插入元素ele
//pop_back();											//删除最后一个元素
//insert(const_iterator pos, ele);						//迭代器指向位置pos插入元素ele
//insert(const_iterator pos, int count, ele);			//迭代器指向位置pos插入count个元素ele
//erase(const_ iterator pos);							//删除迭代器指向的元素
//erase(const_ iterator start, const_ iterator end);	//删除迭代器从start到end之间的元素
//clear();												//删除容器中所有元素

void printVector4(vector<int> v) {
    
    
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
    
    
		cout << *it << " ";
	}
	cout << endl;
}

void test4_01() {
    
    
	vector<int> v1;
	for (int i = 0; i < 10; i++) {
    
    
		v1.push_back(i * 10);
	}
	printVector4(v1);

	//删除尾部元素
	v1.pop_back();
	printVector4(v1);

	//插入元素,参数是迭代器
	v1.insert(v1.begin() + 2, 100);		//在第三个位置插入元素
	printVector4(v1);

	v1.insert(v1.begin(), 2, 1000);		//在首位置插入依次2个1000
	printVector4(v1);

	//删除,参数也是迭代器
	v1.erase(v1.begin());
	printVector4(v1);

	v1.erase(v1.begin(), v1.end() - 5);   //删除指定区间的元素,留下后5个元素
	printVector4(v1);

	//清空容器
	v1.clear();
	printVector4(v1);
}

int main() {
    
    
	test4_01();
	system("pause");
	return 0;
}


2.5 acesso a dados vetoriais

Protótipo de função:

at(int idx);	//返回索引idx所指的数据
operator[];		//返回索引idx所指的数据
front();		//返回容器中第一个数据元素
back();			//返回容器中最后一个数据元素

Exemplo:

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

//at(int idx);	//返回索引idx所指的数据
//operator[];		//返回索引idx所指的数据
//front();		//返回容器中第一个数据元素
//back();			//返回容器中最后一个数据元素

void test5_01() {
    
    
	vector<int> v1;
	for (int i = 0; i < 10; i++) {
    
    
		v1.push_back(i);
	}

	//利用 []
	for (int i = 0; i < v1.size(); i++) {
    
    
		cout << v1[i] << " ";
	}
	cout << endl;

	//利用 at()
	for (int i = 0; i < v1.size(); i++) {
    
    
		cout << v1.at(i) << " ";
	}
	cout << endl;

	//返回第一个元素
	cout << v1.front() << endl;

	//返回最后一个元素
	cout << v1.back() << endl;

}

int main() {
    
    
	test5_01();
	system("pause");
	return 0;
}

2.6 Recipiente intercambiável de vetores, uso inteligente de troca pode reduzir o espaço de memória

Vector suporta troca direta de elementos em dois contêineres.

Protótipo de função:

swap(vec); //将vec与本身的元素互换

E o espaço de memória do objeto vetorial pode ser reduzido por meio da função swap().

Exemplo:

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

//swap(vec); //将vec与本身的元素互换
void printVector6(vector<int>& v) {
    
    
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
    
    
		cout << *it << " ";
	}
	cout << endl;
}

void test6_01() {
    
    
	vector<int> v1,v2;
	for (int i = 0; i < 10; i++) {
    
    
		v1.push_back(i);
		v2.push_back(9-i);
	}
	cout << "交换前" << endl;
	printVector6(v1);
	printVector6(v2);
	
	//v1.swap(v2);
	swap(v1, v2);  //两种都可以
	cout << "交换后" << endl;
	printVector6(v1);
	printVector6(v2);

}
//巧用swap可以收缩内存空间
void test6_02() {
    
    
	vector<int> v;
	for (int i = 0; i < 10000; i++) {
    
    
		v.push_back(i);
	}
	cout << "v的容量为: " << v.capacity() << endl;
	cout << "v的大小为: " << v.size() << endl;

	v.resize(3);
	cout << "v的容量为: " << v.capacity() << endl;  //容量不会收缩
	cout << "v的大小为: " << v.size() << endl;

	//用swap
	//使用匿名对象方法vector<int>(v),这是有参构造将v作为参数传入,因为只穿入元素,所以生成的对象容量和大小都是v的元素个数
	//经过交换,使得v的容量被收缩
	vector<int>(v).swap(v);
	cout << "v的容量为: " << v.capacity() << endl;
	cout << "v的大小为: " << v.size() << endl;
	//同理也可以用此方法指定v的容量和大小
	vector<int>(10).swap(v);
	cout << "v的容量为: " << v.capacity() << endl;
	cout << "v的大小为: " << v.size() << endl;
}

int main() {
    
    
	test6_01();
	test6_02();
	system("pause");
	return 0;
}

2.7 espaço reservado

A finalidade do espaço reservado no vetor é reduzir o número de expansões ao expandir dinamicamente a capacidade.

Protótipo de função:

reserve(int len); //容器预留len个元素长度,预留位置不会初始化,元素不可访问

Exemplo:

#include<iostream>
using namespace std;
#include<vector>
//reserve(int len); //容器预留len个元素长度,预留位置不会初始化,元素不可访问

void test7_01() {
    
    
	vector<int> v;
	int num=0; //统计开辟次数
	int* p = NULL;
	for (int i = 0; i < 100000; i++) {
    
    
		v.push_back(i);
		if (p != &v[0]) {
    
       //每次开辟内存都会改变地址
			p = &v[0];
			num++;
		}
	}
	cout << "开辟了: " << num << "次" << endl;

}

void test7_02() {
    
    
	vector<int> v;
	v.reserve(100000);
	int num = 0; //统计开辟次数
	int* p = NULL;
	for (int i = 0; i < 100000; i++) {
    
    
		v.push_back(i);
		if (p != &v[0]) {
    
       //每次开辟内存都会改变地址
			p = &v[0];
			num++;
		}
	}
	cout << "开辟了: " << num << "次" << endl;
}
int main() {
    
    
	test7_01();
	test7_02();
	system("pause");
	return 0;
}

3 recipientes deque

2.0 deque conceito básico

função :

  • Matriz de extremidade dupla, que pode executar operações de inserção e exclusão no head end

A diferença entre deque e vetor :

  • A inserção e exclusão da cabeça do vetor é ineficiente, e quanto maior o volume de dados, menor a eficiência. Relativamente falando, deque insere e exclui a cabeça mais rápido que vector.
  • A velocidade do vetor acessando os elementos é mais rápida que a do deque (necessidade de usar busca de endereços), que está relacionada à implementação interna dos dois.
    insira a descrição da imagem aqui

O princípio de funcionamento interno do deque: Existe um controlador central
dentro do deque , que mantém o conteúdo em cada buffer e armazena dados reais no buffer. O controlador mantém o endereço de cada buffer, fazendo com que pareça um espaço de memória contínuo ao usar o deque.

insira a descrição da imagem aqui

  • O iterador do contêiner deque também suporta acesso aleatório.

3.1 construtor deque

Protótipo de função:

deque<T> deqT;			//默认构造形式
deque(beg, end);			//构造函数将[beg, end)区间中的元素拷贝给本身。
deque(n, elem);			//构造函数将n个elem拷贝给本身。
deque(const deque& deq);	//拷贝构造函数

Exemplo:

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

void printDeque(deque<int>& d) {
    
    
	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++) {
    
    
		//*it = 100;  #使用const_iterator时不能改变它的值
		cout << *it << " ";
	}
	cout << endl;
}

void test1_01() {
    
    
	deque<int> d1;
	for (int i = 0; i < 10; i++) {
    
    
		d1.push_back(i);
	}
	printDeque(d1);

	deque<int> d2(d1.begin(),d1.end());
	printDeque(d2);

	deque<int> d3(10, 100);
	printDeque(d3);

	deque<int> d4(d3);
	printDeque(d4);


}

int main() {
    
    

	test1_01();
	system("pause");
	return 0;
}

3.2 Operação de atribuição

Protótipo da função (igual ao vetor):

deque& operator=(const deque& deq);
assign(beg, end);
assign(n, elem);  //将n个elem赋值给deque

Exemplo:

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

void printDeque3(const deque<int>&d) {
    
    
	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
    
    
		cout << *it << " ";
	}
	cout << endl;
}
void test3_01() 
{
    
    
	deque<int> d1;
	for (int i = 0; i < 10; i++) {
    
    
		d1.push_back(i);
	}
	printDeque3(d1);
	
	deque<int>d2;
	d2 = d1;
	printDeque3(d2);
	
	deque<int>d3;
	d3.assign(d1.begin(), d1.end());
	printDeque3(d3);

	deque<int>d4;
	d4.assign(10, 100);
	printDeque3(d4);
}

int main()
{
    
    
	test3_01();

	system("pause");
	return 0;
}

3.3 Operação de tamanho

Protótipo de função:

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

Exemplo:

#include<iostream>
#include<deque>
using namespace std;
 
void printDeque3(const deque<int>& d)
{
    
    
	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
    
    
		cout << *it << " ";
	}
	cout << endl;
}
void test3_01() 
{
    
    
	deque<int> d1;
	cout << d1.empty() << endl;
	for (int i = 0; i < 10; i++)
	{
    
    
		d1.push_back(i);
	}
	cout << d1.empty() << endl;
	printDeque3(d1);
	cout << "d1的大小:" << d1.size() << endl;
	//deque没有容量大小,可以一直插入数据

	d1.resize(20);
	printDeque3(d1);
	d1.resize(25, 1);
	printDeque3(d1);
	d1.resize(5);
	printDeque3(d1);
}

int main()
{
    
    
	test3_01();
	system("pause");
	return 0;
}

3.4 Inserção e exclusão

Protótipo de função:

Insira a operação em ambas as extremidades:

push_back(elem) ;		在容器尾部添加一个数据
push_front(elem );		在容器头部插入一个数据
pop_back();				删除容器最后一个数据
pop_front( ) ;			删除容器第一个数据

Operação de posição especificada:

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位置的数据,返回下一个数据的位置。

Exemplo:

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

void printDeque4(const deque<int>& d)
{
    
    
	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
    
    
		cout << *it << " ";
	}
	cout << endl;
}

void test4_01()
{
    
    
	deque<int> d1;
	//尾插
	d1.push_back(10);
	d1.push_back(20);

	//头插
	d1.push_front(100);
	d1.push_front(200);
	printDeque4(d1);

	//尾删
	d1.pop_back();
	printDeque4(d1);
	//头删
	d1.pop_front();
	cout << "d1" << endl;
	printDeque4(d1);
	
	deque<int> d2;
	d2.push_back(10);
	d2.push_back(20);
	d2.push_front(100);
	d2.push_front(200);
	cout << "d2" << endl;
	printDeque4(d2);
	d2.insert(d2.begin(), 1000);
	printDeque4(d2);
	d2.insert(d2.begin(), 5,10000);
	printDeque4(d2);

	//按照区间插入
	deque<int> d3;
	d3.push_back(1);
	d3.push_back(2);
	d3.push_back(3);
	cout << "d3" << endl;
	printDeque4(d3);
	d3.insert(d3.begin(), d1.begin(), d1.end()); //(pos,[begin,end))
	printDeque4(d3);

	//删除
	deque<int>::iterator it = d3.begin();
	it++;
	d3.erase(it);
	printDeque4(d3);
	//按区间方式删除
	d3.erase(d3.begin(), d3.end());  //和d3.clear()效果一样
	printDeque4(d3);

}

int main()
{
    
    
	test4_01();
	system("pause");
	return 0;
}

3.5 Acesso a Dados

Protótipo de função:

at(int idx);		//返回索引idx所指的数据
operator[];			//返回索引idx所指的数据
front(); 			//饭回容器中第一个数据元素
back(); 			//返回容器中最后一个数据元素

Exemplo:

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

void test5_01()
{
    
    
	deque<int> d;
	d.push_back(1);
	d.push_back(2);
	d.push_back(3);
	d.push_front(100);
	d.push_front(200);
	d.push_front(300);
	for (int i = 0; i < d.size(); i++)
	{
    
    
		cout << d[i] << " ";
	}
	cout << endl;
	for (int i = 0; i < d.size(); i++)
	{
    
    
		cout << d.at((d.size()-1) - i) << " ";
	}
	cout << endl;

	cout << "第一个元素为:" << d.front() << endl;
	cout << "最后的元素为:" << d.back() << endl;
}

int main()
{
    
    
	test5_01();
	system("pause");
	return 0;
}

3.6 classificação deque

Protótipo de função:

#include<algorithm>
sort(iterator beg, iterator end) ll对beg和end区间内元素进行排序

sort pode ser usado com qualquer contêiner que suporte iteradores de acesso aleatório.
Um iterador de acesso aleatório significa que a posição apontada pelo iterador pode ser movida para frente ou para trás em n posições, e os dados do contêiner também podem ser obtidos.
Ao julgar, podemos julgar se o iterador do contêiner é um iterador de acesso aleatório, julgando se o iterador do contêiner suporta a operação "+n". Os iteradores de vetor, deque e string suportam acesso aleatório, mas os iteradores de lista não.

Exemplo:

#include<iostream>
#include<deque>
#include<algorithm>
using namespace std;

void printDeque6(deque<int>& d)
{
    
    
	for (deque<int>::iterator it = d.begin(); it != d.end(); it++)
	{
    
    
		cout << *it << " ";
	}
	cout << endl;
}

void test6_01()
{
    
    
	deque<int> d;
	d.push_back(10);
	d.push_back(20);
	d.push_back(3);
	d.push_front(200);
	d.push_front(500);
	d.push_front(300);

	printDeque6(d);
	//默认升序
	//对于支持随机访问迭代器的容器都可以使用sort.
	//deque,vector,
	sort(d.begin(), d.end());
	printDeque6(d);
}

int main()
{
    
    
	test6_01();
	system("pause");
	return 0;
}

Acho que você gosta

Origin blog.csdn.net/qq_49030008/article/details/123672670
Recomendado
Clasificación