[toc]
- 本阶段主要针对 c++泛型编程和 STL 技术做详细讲解,探讨 c++更深层的使用
模板就是建立通用的模具,大大提高复用性
模板的特点:
- 模板不可以直接使用,它只是一个框架
- 模板的通用并不是万能的
- c++另一种编程思想称为泛型编程,主要利用的技术就是模板
- c++提供两种模板机制:函数模板和类模板
函数模板作用:
建立一个通用函数,其函数返回值类型和形参类型可以不具体指定,用一个虚拟的类型来代表
语法:
template
函数声明或定义
解释:
template---声明创建模板
typename---表面其后面的符号是一种数据类型,可以用 class 代替
T ---通用的数据类型,名称可以替换,通常为大写字母
#include <iostream>
using namespace std;
template<typename T> //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
void mySwap(T &a,T &b)
{
T temp =a;
a=b;
b=temp;
}
void test01()
{
int a=10;
int b=20;
//自动类型推导
// mySwap(a,b);
//显示指定类型
mySwap<int>(a,b);
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
int main() {
test01();
system("pause");
return 0;
}
总结:
- 函数模板利用关键字 template
- 使用函数模板有两种方式:自动类型推导、显示指定类型
- 模板的目的是为了提高复用性,将类型参数化
注意事项:
- 自动类型推导,必须推导出一只的数据类型 T,才可以使用
- 模板必须要确定出 T 的数据类型,才可以使用
#include <iostream>
using namespace std;
//函数模板注意事项
template<class T> //typename可以特换成class
void mySwap(T&a,T&b)
{
T temp =a;
a=b;
b=temp;
}
//1、自动类型推导,必须推导出一只的数据类型T才可以使用
void test01(){
int a=10;
int b=20;
//char c='c'
mySwap(a,b);//正确!
//mySwap(a,c);//错误!推导不出一只的T类型
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
//2、模板必须要确定出T的数据类型,才可以使用
template<class T>
void func()
{
cout<<"func调用"<<endl;
}
void test02(){
//func(); //错误!
func<int>();
}
int main(){
test01();
test02();
system("pause");
return 0;
}
总结:
- 使用模板是必须确定出通用数据类型 T,并且能够推导出一只的类型
案例描述:
- 利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序
- 排序规则从大到小,排序算法为选择排序
- 分别利用插入数组和 ing 数组进行测试
示例:
#include<iostream>
using namespace std;
//实现通用 对数组进行排序的函数
//规则 从大到小
//算法 选择
//测试 char数组 int数组
//交换函数模板
template<class T>
void mySwap(T&a,T&b)
{
T temp=a;
a=b;
b=temp;
}
//排序算法
template<class T>
void mySort(T arr[],int len)
{
for(int i=0;i<len;i++)
{
int max=i;
for(int j=i+1;j<len;j++)
{
//认定最大值 比 遍历出的数值要打,说明j下标的元素才是真正的最大值
if(arr[max]<arr[j])
{
max=j;//更新最大值下标
}
}
if(max!=i)
{
//交换和i元素
mySwap(arr[max],arr[i]);
}
}
}
//提供打印数组模板
template<class T>
void printArray(T arr[],int len)
{
for(int i=0;i<len;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
void test01()
{
//测试char数组
char charArr[]="badcfe";
int num=sizeof(charArr)/sizeof(char);
mySort(charArr,num);
printArray(charArr,num);
}
void test02(){
//测试int数组
int intArr[]={7,5,1,3,9,2,4,6,8};
int num= sizeof(intArr)/ sizeof(int);
mySort(intArr,num);
printArray(intArr,num);
}
int main() {
test01();
test02();
system("pause");
return 0;
}
普通函数与函数模板区别:
- 普通函数调用时可以发生自动类型转换(隐式类型转换)
- 函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
- 如果利用显示指定类型方式,可以发生隐式类型转换
示例:
#include<iostream>
using namespace std;
//普通函数
int myAdd01(int a,int b)
{
return a+b;
}
//函数模板
template <class T>
T myAdd02(T a,T b)
{
return a+b;
}
//使用函数模板是,如果用自动类型推导,不会发生自动类型转换,即隐式类型转换
void test01()
{
int a=10;
int b=20;
char c='c';
cout<<myAdd01(a,b)<<endl;
//自动类型推导
cout<<myAdd01(a,c)<<endl;
//显示指定类型
cout<<myAdd02<int>(a,c)<<endl;
}
int main() {
test01();
system("pause");
return 0;
}
总结:建议使用显示指定类型的方式,调用函数模板,因为可以自己确定调用类型 T
调用规则如下:
- 如果函数模板和普通函数都可以实现,优先调用普通函数
- 可以通过空模板参数列表来强制调用函数模板
- 函数模板也可以发生重载
- 如果函数模板可以产生更好的匹配,优先调用函数模板
示例:
#include<iostream>
using namespace std;
//普通函数与函数模板调用规则
void myPrint(int a,int b)
{
cout<<"调用普通函数"<<endl;
}
template <typename T>
void myPrint(T a,T b,T c)
{
cout<<"调用的模板"<<endl;
}
void test01()
{
int a=10;
int b=10;
// myPrint(a,b,100);
//通过空模板参数列表,强制调用函数模板
// myPrint<>(a,b);
//如果函数模板产生更好的匹配,优先调用函数模板
char c1='a';
char c2='b';
myPrint(c1,c2);
}
int main() {
test01();
system("pause");
return 0;
}
局限性:
- 模板的通用性并不是万能的
例如:
template<class T>
void f(T a,T b)
{
a=b;
}
在上述代码中提供的赋值操作,如果转入的 a 和 b 是一个数组,就无法实现
再例如:
template<class T>
void f(T a,T b)
{
if(a>b){...}
}
在上述代码中,如果 T 的数据类型传入的是像 Person 这样的自定义数据类型,也无法正常运行
因此 c++为了解决这种问题,提供模板的重载,可以为这些特定类型提供具体化的模板
#include<iostream>
using namespace std;
#include <string>
class Person
{
public:
Person(string name,int age){
this->m_Name=name;
this->m_Age=age;
}
//姓名
string m_Name;
//年龄
int m_Age;
};
template<class T>
bool myCompare(T &a,T &b)
{
if(a==b)
{
return true;
}
else
{
return false;
}
}
//利用具体化Person的版本实现代码,具体化优先调用
template<> bool myCompare(Person &p1,Person &p2)
{
if(p1.m_Name==p2.m_Name &&p1.m_Age==p2.m_Age)
{
return true;
}
else
{
return false;
}
}
void test01()
{
int a=10;
int b=20;
bool ret=myCompare(a,b);
if(ret)
{
cout<<"a==b"<<endl;
}
else
{
cout<<"a!=b"<<endl;
}
}
void test02()
{
Person p1("Tom",10);
Person p2("Tom",11);
bool ret=myCompare(p1,p2);
if(ret)
{
cout<<"p1==p2"<<endl;
}
else
{
cout<<"p1!=p2"<<endl;
}
}
int main() {
test01();
test02();
system("pause");
return 0;
}
总结:
- 利用具体化的模板,可以解决自定义类型的通用化
- 学习模板并不是为了写模板,而是在 STL 能够运用系统提供的模板
类模板作用:
- 建立一个通用类,类中的成员 数据类型可以不具体指定,用一个虚拟的类型来代表
语法:
template
类
解释:
template ---声明创建模板
typename ---表面其后面的符号一种数据类型,可以用 class 代替
T ---通用的数据类型,名称可以替换,通常为大写字母
#include<iostream>
using namespace std;
#include <string>
template <class NameType,class AgeType>
class Person
{
public:
Person(NameType name,AgeType age)
{
this->m_Name=name;
this->m_Age=age;
}
void showPerson()
{
cout<<"name: "<<this->m_Name<<" 年龄: "<<this->m_Age<<endl;
}
//姓名
NameType m_Name;
//年龄
AgeType m_Age;
};
void test01()
{
Person<string,int> p1("孙悟空",999);
p1.showPerson();
}
int main() {
test01();
system("pause");
return 0;
}
总结:类模板和函数模板语法相似,在声明模板 template 后面加类,此类称为类模板
类模板与函数模板区别主要有两点
- 类模板没有自动类型推导的使用方式
- 类模板在模板参数列表中可以有默认参数
示例:
template <class NameType,class AgeType=int>
class Person
{
public:
Person(NameType name,AgeType age)
{
this->m_Name=name;
this->m_Age=age;
}
void showPerson()
{
cout<<"name: "<<this->m_Name<<" 年龄: "<<this->m_Age<<endl;
}
//姓名
NameType m_Name;
//年龄
AgeType m_Age;
};
void test01()
{
Person<string int>p("孙悟空",1000);
p.showPerson();
}
void test02()
{
Person<string>p("猪八戒",1000);
p.showPerson();
}
类模板中成员函数和普通类中成员函数创建时间是有区别的:
- 普通类中的成员函数一开始就可以创建
- 类模板中的成员函数在调用是才创建
示例:
class Person1()
{
public:
void showPerson1()
{
cout<<"Person1 show"<<endl;
}
};
class Person2()
{
public:
void showPerson2()
{
cout<<"Person2 show"<<endl;
}
};
template<class T>
class MyClass
{
public:
T obj;
//类模板中的成员函数
void func1(){
obj.showPerson1();
}
void func2(){
obj.showPerson2();
}
};
void test01()
{
MyClass<Person1>m;
m.func1();
//m.func2();//编译器会出错,说明函数调用才会去创建成员函数
}
总结:类模板中的成员函数并不是一开始就创建的,在调用是才去创建
学习目标:
- 类模板实例化出的对象,向函数传参的方式
一共有三种传入方式
- 指定传入的类型 ---直接显示对象数据类型
- 参数模板化 ---将对象中的参数变为模板进行传递
- 整个类模板化 ---将这个对象类型 模板化进行传递
示例:
#include<iostream>
using namespace std;
#include<string>
//类模板对象做函数参数
template<class T1,class T2>
class Person
{
public:
Person(T1 name,T2 age)
{
this->m_Name=name;
this->m_Age=age;
}
void showPerson()
{
cout<<"姓名:"<<this->m_Name<<"年龄:"<<this->m_Age<<endl;
}
T1 m_Name;
T2 m_Age;
};
//1、指定传入类型
void printPerson1(Person<string,int>&p)
{
p.showPerson();
}
void test01()
{
Person<string,int>p("孙悟空",100);
printPerson1(p);
}
//2、参数模板化
template<class T1,class T2>
void printPerson2(Person<T1,T2>&p)
{
p.showPerson();
cout<<"T1的类型为:"<<typeid(T1).name()<<endl;
cout<<"T1的类型为:"<<typeid(T2).name()<<endl;
}
void test02()
{
Person<string,int>p("猪八戒",90);
}
//3、整个类模板化
template<class T>
void printPerson3(T &p)
{
p.showPerson();
cout<<"T的数据类型为:"<<typeid(T).name()<<endl;
}
void test03()
{
Person<string,int>p("唐僧",40);
printPerson3(p)
}
int main(){
test01();
test02();
test03();
system("pause");
return 0;
}
当类模板碰到继承时,需要注意一下几点:
- 当子类继承父类是一个类模板是,子类在声明的时候,要指定父类中 T 的类型
- 如果不指定,编译器无法给子类分配内存
- 如果想灵活指定出父类中 T 的类型,子类也需要变为类模板
示例:
#include<iostream>
using namespace std;
template<class T>
class Base
{
T m;
};
class Son :public Base<int> //必须指定数据类型
{
};
void test01()
{
Son s1;
}
//如果想灵活指定父类中T类型,子类也需要变类模板
template<class T1,class T2>
class Son2 :public Base<T2> //必须指定数据类型
{
public:
Son2()
{
cout<<"T1的类型为:"<<typeid(T1).name()<<endl;
cout<<"T2的类型为:"<<typeid(T2).name()<<endl;
}
T1 obj;
};
void test01()
{
Son2<int,char> s2;
}
//....运行
总结:如果父类是类模板,子类需要指定出父类中 T 的数据类型
学习目标:能够掌握类模板中的成员函数类外实现
示例:
#include<iostream>
using namespace std;
#include<string>
//类模板成员函数类外实现
template<class T1,class T2>
class Person
{
public:
Person(T1 name,T2 age);
void showPerson();
T1 m_Name;
T2 m_Age;
};
//构造函数类外实现
template<class T1,class T2>
Person<T1,T2>::Person(T1 name,T2 age)
{
this->m_Name=name;
this->m_Age=age;
}
//成员函数类外实现
template<class T1,class T2>
void Person<T1,T2>::showPerson()
{
cout<<"姓名:"<<this->m_Name<<"年龄:"<<this->m_Age<<endl;
}
void test01()
{
Person<string,int> p("Tom",20)
p.showPerson();
}
int main(){
test01();
system("pause");
return 0;
}
学习目标:
- 掌握类模板成员函数分文件编写产生的问题以及解决方式
问题:
- 类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到
解决:
- 解决方式 1:直接包含.cpp 源文件
- 解决方式 2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp 是约定的名称,并不是强制
示例:
//第一种解决方式直接包含源文件
//person.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
template <class T1,class T2>
class Person
{
public:
Person(T1 name,T2 age);
void showPerson();
T1 m_Name;
T2 m_Age;
};
//person.cpp
#include "person.h"
template <class T1,class T2>
Person<T1,T2>::Person(T1 name, T2 age) {
this->m_Name=name;
this->m_Age=age;
}
template <class T1,class T2>
void Person<T1,T2>::showPerson() {
cout<<"姓名:"<<this->m_Name<<" 年龄:"<<this->m_Age<<endl;
}
//main.cpp
#include<iostream>
using namespace std;
#include "person.cpp"
void test01(){
Person<string,int >p("tom",17);
p.showPerson();
}
int main() {
test01();
system("pause");
return 0;
}
//第二种解决方式,将.h和.cpp中的内容写到一起,将后缀名改为.hpp文件
//person.hpp
#pragma once
#include <iostream>
#include <string>
using namespace std;
template <class T1,class T2>
class Person
{
public:
Person(T1 name,T2 age);
void showPerson();
T1 m_Name;
T2 m_Age;
};
template <class T1,class T2>
Person<T1,T2>::Person(T1 name, T2 age) {
this->m_Name=name;
this->m_Age=age;
}
template <class T1,class T2>
void Person<T1,T2>::showPerson() {
cout<<"姓名:"<<this->m_Name<<" 年龄:"<<this->m_Age<<endl;
}
//main.cpp
#include<iostream>
using namespace std;
//第二种解决方式,将.h和.cpp中的内容写到一起,将后缀名改为.hpp文件
#include "person.hpp"
void test01(){
Person<string,int >p("tom",17);
p.showPerson();
}
int main() {
test01();
system("pause");
return 0;
}
总结:主流的解决方式是第二种,将类模板成员函数写到一起,并将后缀名改为.hpp
学习目标:
- 掌握类模板配合友元函数的类内和类外实现
全局函数类内实现-直接在类内声明友元即可
全局函数类外实现-需要提前让编译器知道全局函数的存在
示例:
#include<iostream>
using namespace std;
#include <string>
template <class T1,class T2>
class Person;
//类外实现
template<class T1,class T2>
void printPerson2(Person<T1,T2> p)
{
cout<<"类外实现---姓名:"<<p.m_Name<<" 类外实现---年龄:"<<p.m_Age<<endl;
}
//通过全局函数 打印Person信息
template <class T1,class T2>
class Person
{
friend void printPerson(Person<T1,T2> p)
{
cout<<"姓名:"<<p.m_Name<<" 年龄:"<<p.m_Age<<endl;
}
//全局函数 类外实现
//加空模板参数列表
//如果全局函数是类外实现,需要让编译器提前知道这个函数的存在
friend void printPerson2<>(Person<T1,T2> p);
public:
Person(T1 name,T2 age)
{
this->m_Name=name;
this->m_Age=age;
}
private:
T1 m_Name;
T2 m_Age;
};
//1、全局函数在类内实现
void test01(){
Person<string,int>p("Tom",20);
printPerson(p);
}
//2、全局函数在类外实现
void test02(){
Person<string,int>p("Jim",20);
printPerson2(p);
}
int main() {
test01();
test02();
system("pause");
return 0;
}
总结:建议全局函数做类内实现,用法简单,而且编译器可以直接识别
案例描述:实现一个通用的数组类,要求如下:
- 可以对内值数据类型以及自定义数据类型的数据进行存储
- 将数组中的数据存储到堆区
- 构造函数中可以传入数组的容量
- 提供对应的拷贝构造函数以及 operator=防止浅拷贝问题
- 提供尾插法和尾删法对数组中的数据进行增加和删除
- 可以通过下标的方式访问数组中的元素
- 可以获取数组中当前元素个数和数组的容量
示例:
myArray.hpp 中代码
//自己的通用的数组类
#pragma once
#include <iostream>
using namespace std;
template <class T>
class MyArray {
public:
//有参构造 参数 容量
MyArray(int capacity)
{
//cout<<"MyArray有参构造调用"<<endl;
this->m_Capacity=capacity;
this->m_Size=0;
this->pAddress=new T[this->m_Capacity];
}
//拷贝构造
MyArray(const MyArray& arr)
{
//cout<<"MyArray拷贝构造调用"<<endl;
this->m_Capacity=arr.m_Capacity;
this->m_Size=arr.m_Size;
//this->pAddress=arr.pAddress;
//深拷贝
this->pAddress=new T[arr.m_Capacity];
//将arr中的数据都拷贝过来
for(int i=0;i<this->m_Size;i++)
{
this->pAddress[i]=arr.pAddress[i];
}
}
//operator=防止浅拷贝问题
MyArray& operator=(const MyArray& arr)
{
//cout<<"MyArray中operator的调用"<<endl;
//先判断原来堆区是否有数据,如果有限释放
if(this->pAddress!=NULL)
{
delete[] this->pAddress;
this->pAddress=NULL;
this->m_Capacity=0;
this->m_Size=0;
}
//深拷贝
this->m_Capacity=arr.m_Capacity;
this->m_Size=arr.m_Size;
this->pAddress=new T[arr.m_Capacity];
for(int i=0;i<this->m_Size;i++)
{
this->pAddress[i]=arr.pAddress[i];
}
return * this;
}
//尾插法
void Push_Back(const T & val)
{
//判断容量是否等于大小
if(this->m_Capacity==this->m_Size)
{
return;
}
this->pAddress[this->m_Size]=val;
this->m_Size++;//更新数组大小
}
//尾删法
void Pop_Back()
{
//让用户访问不到最后一个元素,即为尾删,逻辑删除
if(this->m_Size==0)
{
return;
}
this->m_Size--;
}
//通过下标方式访问数组中的元素
T operator[](int index)
{
return this->pAddress[index];
}
//返回数组容量
int getCapacity()
{
return this->m_Capacity;
}
//返回数组大小
int getSize()
{
return this->m_Size;
}
//析构函数
~MyArray()
{
//cout<<"MyArray析构函数调用"<<endl;
if(this->pAddress!=NULL)
{
delete[] this->pAddress;
this->pAddress=NULL;
}
}
private:
T * pAddress;//指针指向堆区开辟的真实数组
int m_Capacity;//数组容量
int m_Size;//数组大小
};
测试 main.cpp
#include<iostream>
using namespace std;
#include <string>
#include "MyArray.hpp"
void printIntArray(MyArray <int>& arr)
{
for (int i = 0; i <arr.getSize(); ++i) {
cout<<arr[i]<<endl;
}
}
void test01()
{
MyArray <int>arr1(5);
for (int i = 0; i <5; ++i) {
//利用尾插法向数组中插入数据
arr1.Push_Back(i);
}
cout<<"arr1的打印输出为:"<<endl;
printIntArray(arr1);
cout<<"arr1的容量为:" << arr1.getCapacity()<<endl;
cout<<"arr1的大小为:" << arr1.getSize()<<endl;
cout<<"arr2的打印输出为:"<<endl;
MyArray <int>arr2(arr1);
printIntArray(arr2);
//尾删
arr2.Pop_Back();
cout<<"arr2的容量为:" << arr2.getCapacity()<<endl;
cout<<"arr2的大小为:" << arr2.getSize()<<endl;
}
//测试自定义数据类型
class Person
{
public:
Person(){};
Person(string name,int age)
{
this->m_Age=age;
this->m_Name=name;
}
string m_Name;
int m_Age;
};
void printPersonArray(MyArray<Person>& arr)
{
for(int i=0;i<arr.getSize();i++)
{
cout<<"姓名:"<<arr[i].m_Name<<" 年龄:"<<arr[i].m_Age<<endl;
}
}
void test02()
{
MyArray<Person> arr(10);
Person p1("张三",20);
Person p2("李四",21);
Person p3("王五",22);
Person p4("赵六",23);
Person p5("刘七",24);
//将数据插入到数组中
arr.Push_Back(p1);
arr.Push_Back(p2);
arr.Push_Back(p3);
arr.Push_Back(p4);
arr.Push_Back(p5);
//打印数组
printPersonArray(arr);
//输出容量
cout<<"arr容量为:"<<arr.getCapacity()<<endl;
//输出大小
cout<<"arr大小为:"<<arr.getSize()<<endl;
}
int main() {
// test01();
test02();
system("pause");
return 0;
}
总结:能够利用所学习知识点实现通用的数组
- 长久以来,软件界一直希望建立一种可重复利用的东西
- c++的面向对象和泛型编程思想,目的就是复用性的提升
- 大多情况下,数据结构和算法都未能有一套标准,导致被迫从事大量重复工作
- 为了建立数据结构和算法的一套标准,诞生了 STL
- STL(Standard Template Library,标准模板库)
- STL 从广义上分为:容器(container)算法(algorithm)迭代器(iterator)
- 容器和算法之间通过迭代器进行无缝连接
- STL 几乎所有的代码都采用了模板类或者模板函数
STL 大体分为六大组件,分别是:容器、算法、迭代器、仿函数、适配器(配接器)、空间配置器
- 容器:各种数据结构,如 vector、list、deque、set、map 等,用来存放数据
- 算法:各种常用的算法,如 sort、find、copy、for_each 等
- 迭代器:扮演了容器与算法之间的胶合剂
- 仿函数:行为类似函数,可以作为算法的某种策略
- 适配器:一种用来修饰修饰容器或者仿函数或迭代器接口的东西
- 空间配置器:负责空间的配置与管理
容器:置物之所也
STL 容器就是将运用最广泛的一些数据结构实现出来
常用的数据结构:数组,链表,树,栈,队列,集合,映射表 等
这些容器分为序列式容器和关联式容器两种
- 序列式容器:强调值得排序,序列式容器中的每个元素均有固定的位置
- 关联式容器:二叉树结构,各元素之间没有严格的物理上的顺序关系
算法:问题之解法也
有限的步骤,解决逻辑或数学上的问题,这一门学科我们叫做算法
算法分为:质变算法和非质变算法。
质变算法:是指运算过程中会更改区间内的元素的内容,列如拷贝,替换,删除等等
非质变算法:是指运算过程中不会更改区间内的元素内容,列如查找,计算,遍历,寻找极值等等
迭代器:容器和算法之间粘合剂
提供一种方法,使之能够依序寻访某个容器所含的各个元素,而又无须暴露该容器的内部表达方式。
每个容器都有自己专属的迭代器
迭代器使用非常类似于指针,初学阶段我们可以先理解迭代器为指针
迭代器种类:
种类 | 功能 | 支持运算 |
---|---|---|
输入迭代器 | 对数据的只读访问 | 只读,支持++、==、!、= |
输出迭代器 | 对数据的只写访问 | 只写,支持++ |
前向迭代器 | 读写操作,并能向前推进迭代器 | 读写,支持++、==、!、= |
双向迭代器 | 读写操作,并能向前和向后操作 | 读写,支持++、--, |
随机访问迭代器 | 读写操作,可以以跳跃的方式访问任意数据,功能最强的迭代器 | 读写,支持++、--、[n]、-n、<、<=、>、>= |
常用的容器中迭代器种类为双向迭代器,和随机访问迭代器
了解 STL 中容器、算法、迭代器概念之后,我们利用代码感受 STL 的魅力
STL 中最常用的容器为 Vector,可以理解为数组,下面我们将学习如何向这个容器中插入数据,并遍历这个容器
容器:vector
算法:for_each
迭代器:vector::iterator
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>//标准算法头文件
//vector容器存放内置数据类型
//打印函数
void myPrint(int val)
{
cout<<val<<endl;
}
void test01()
{
//创建了一个vector容器,数组
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 it=v.begin();it!=v.end();it++)
// {
// cout<<*it<<endl;
// }
//第三种遍历方式 利用STL提供遍历算法
for_each(v.begin(),v.end(),myPrint);
}
int main() {
test01();
system("pause");
return 0;
}
学习目标:vector 中存放自定义数据类型,并打印输出
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <string>
//vector容器中存放自定义数据类型
class Person{
public:
Person(string name,int age)
{
mName=name;
mAge=age;
}
public:
string mName;
int mAge;
};
void test01()
{
vector<Person> v;
Person p1("aaa",10);
Person p2("bbb",20);
Person p3("ccc",30);
Person p4("ddd",40);
Person p5("eee",50);
//向容器中添加数据
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
//遍历容器中的数据
for(vector<Person>::iterator it=v.begin();it!=v.end();it++)
{
// cout<<"姓名:"<<(*it).mName<<" 年龄:"<<(*it).mAge<<endl;
cout<<"姓名:"<<it->mName<<" 年龄:"<<it->mAge<<endl;
}
}
//存放自定义数据类型 指针
void test02()
{
vector<Person*> v;
Person p1("aaa",10);
Person p2("bbb",20);
Person p3("ccc",30);
Person p4("ddd",40);
Person p5("eee",50);
//向容器中添加数据
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
v.push_back(&p5);
//遍历容器
for(vector<Person *>::iterator it=v.begin();it!=v.end();it++)
{
cout<<"姓名:"<<(*it)->mName<<" 年龄:"<<(*it)->mAge<<endl;
}
}
int main() {
// test01();
test02();
system("pause");
return 0;
}
学习目标:容器中嵌套容器,我们将所有数据进行遍历输出
示例:
#include<iostream>
using namespace std;
#include <vector>
//容器嵌套容器
void test01()
{
vector<vector<int>> v;
//创建小容器
vector<int> v1;
vector<int> v2;
vector<int> v3;
vector<int> v4;
//向小容器中添加数据
for (int i = 0; i <4;i++) {
v1.push_back(i+1);
v2.push_back(i+2);
v3.push_back(i+3);
v4.push_back(i+4);
}
//将小容器插入到大容器中
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
v.push_back(v4);
//通过大容器,吧所有数据遍历一遍
for(vector<vector<int>>::iterator it=v.begin();it!=v.end();it++)
{
//(*it)---容器vector<int>
for(vector<int>::iterator vit=(*it).begin();vit!=(*it).end();vit++)
{
cout<<*vit<<" ";
}
cout<<endl;
}
}
int main() {
test01();
system("pause");
return 0;
}
本质:
- string 是 c++风格的字符串,而 string 本质上是一个类
string 和 char *区别
- char *是一个指针
- string 是一个类,类内部封装了 char*,管理这个字符串,是一个 char * 型的容器,
特点:
string 类内部封装了很多成员方法
例如:查找 find,拷贝 copy,删除 delete,替换 replace,插入 insert
string 管理 char *所分配的内存,不用担心复制越界和取值越界等,有类内部进行负责
构造函数原型:
- string() //创建一个空的字符串 例如:string str;
- string(const char* s); //使用字符串 s 初始化
- string(string string& str); //使用一个 string 对象初始化另一个 string 对象
- string(int n,char c); //使用 n 个字符 c 初始化
#include<iostream>
using namespace std;
#include<string>
void test01()
{
string s1;//默认构造
const char * str="hello world";
string s2(str);
cout<<"s2="<<s2<<endl;
string s3(s2);
cout<<"s3="<<s3<<endl;
string s4(10,'a');
cout<<"s4="s4<<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
总结:string 的多种构造方式没有可比性,灵活使用即可
功能描述:
- 给 string 字符串进行赋值
赋值的函数原型:
- 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 赋给当前字符串
#include<iostream>
using namespace std;
#include<string>
//string赋值操作
void test01()
{
string str1;
str1="hello world";
cout<<"str1="<<str1<<endl;
string str2;
str2=str1;
cout<<"str2="<<str2<<endl;
string str3;
str3='a';
cout<<"str3="<<str3<<endl;
string str4;
str4.assign("hello C++");
cout<<"str4="<<str4<<endl;
string str5;
str5.assign("hello C++",5);
cout<<"str5="<<str5<<endl;
string str6;
str6.assign(str5);
cout<<"str6="<<str6<<endl;
string str7;
str7.assign(10,'w');
cout<<"str7="<<str7<<endl;
}
int main() {
test01();
system("pause");
return 0;
}
功能描述:
- 实现在字符串末尾拼接字符串
函数原型:
- 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 个字符连接到字符串结尾
#include<iostream>
using namespace std;
#include<string>
//string赋值操作
void test01()
{
string str1="我";
str1+="爱玩游戏";
cout<<str1<<endl;
str1+=":";
cout<<str1<<endl;
string str2="LOL DNF";
str1+=str2;
cout<<str1<<endl;
string str3="I";
str3.append(" love ");
cout<<str3<<endl;
str3.append("game abcde",4);
cout<<str3<<endl;
str3.append(str2);
cout<<str3<<endl;
str3.append(str2,4,3);
cout<<str3<<endl;
}
int main() {
test01();
system("pause");
return 0;
}
功能描述:
- 查找:查找指定字符串是否存放
- 替换:在指定的位置替换字符串
函数原型:
- 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
示例:
#include<iostream>
using namespace std;
#include<string>
//字符串查找
void test01()
{
string str1="abcdefg";
int pos=str1.find("de");
if(pos==-1)
{
cout<<"未找到字符串"<<endl;
}else
{
cout<<"pos="<<pos<<endl;
}
//rfind
//rfind从右往左查找 find从左往右查找
pos=str1.rfind("de");
cout<<"pos="<<pos<<endl;
}
void test02()
{
string str1="abcdefg";
//从1号位置起 3个字符 替换为“1111”
str1.replace(1,3,"111");
cout<<str1<<endl;
}
int main() {
test02();
system("pause");
return 0;
}
总结:
- find 查找是从左往后,rfind 从右往左
- find 找到字符串后返回查找的第一个字符位置,找不到返回-1
- replace 在替换时,要指定从哪个位置起,多少个字符,替换成什么样的字符串
功能描述:
- 字符串之间的比较
比较方式:
- 字符串比较是按字符的 ASCII 码进行对比
=返回 0
>返回 1
< 返回 -1
函数原型:
- int compare(const string &s) const;//与字符串 s 比较
- int compare(const char *s) const;//与字符串 s 比较
#include<iostream>
using namespace std;
#include<string>
//字符串比较
void test01()
{
string str1="hello";
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 main()
{
test01();
system("pause");
return 0;
}
string 中单个字符存取方式有两种
- char& operator[](int n); //通过[]方式取字符
- char& at(int n); //通过 at 方法获取字符
#include<iostream>
using namespace std;
#include<string>
//字符串查找
void test01()
{
string str ="hello world";
//通过[]访问单个字符
for(int i=0;i<str.size();i++)
{
cout<<str[i]<<" ";
}
cout<<endl;
//通过at方式访问单个字符
for (int j = 0; j < str.size();j++) {
cout<<str.at(j)<<" ";
}
cout<<endl;
//修改单个字符
str[0]='x';
cout<<str<<endl;
str.at(1)='x';
cout<<str<<endl;
}
int main() {
test01();
system("pause");
return 0;
}
功能描述:
- 对 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=nops); //删除从 pos 开始的 n 个字符
#include<iostream>
using namespace std;
#include<string>
//string插入和删除
void test01()
{
//插入
string str="hello";
str.insert(1,"111");
cout<<str<<endl;
//删除
str.erase(1,3);
cout<<str<<endl;
}
int main() {
test01();
system("pause");
return 0;
}
总结:插入和删除的起始下标都是从 0 开始
3.1.9 string 子串
功能描述:
- 从字符串中获取想要的子串
函数原型:
- string substr(int pos=0;int n=npos) const; //返回由 pos 开始的 n 个字符组成的字符串
#include<iostream>
using namespace std;
#include<string>
//string求子串
void test01()
{
string str="abcdef";
string subStr=str.substr(1,3);
cout<<"subStr="<<subStr<<endl;
}
//使用操作
void test02()
{
string email="[email protected]";
//从邮件地址中获取用户名信息
int pos=email.find("@");
cout<<pos<<endl;
string usrName=email.substr(0,pos);
cout<<usrName<<endl;
}
int main() {
test02();
system("pause");
return 0;
}
总结:灵活的运用求子串功能,可以在实际开发中获取有效的信息
功能:
- vector 数据结构和数组非常相似,也称为单端数组
vector 与普通数组区别:
- 不同之处在与数组是静态空间,而 vector 可以动态扩展
动态扩展:
- 并不是在原空间之后续接新空间,而是找更大的内存空间,然后将原数据拷贝新空间,释放原空间
- vector 容器的迭代器是支持随机访问的迭代器
功能描述:
- 创建 vector 容器
函数原理:
- vector< T > v; //采用模板实现类实现,默认构造函数
- vector(v.begin(),v.end()); //将 v[begin(),end()]区间中的元素拷贝给本身
- vector(n,elem); //构造函数将 n 个 elem 拷贝给本身
- vector(const vector &vec); //拷贝构造函数
示例:
#include<iostream>
using namespace std;
#include<string>
#include <vector>
//vector容器构造
void printVactor(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);
}
printVactor(v1);
//通过区间方式进行构造
vector<int>v2(v1.begin(),v1.end());
printVactor(v2);
//n个elem方式构造
vector<int>v3(10,100);
printVactor(v3);
//拷贝构造
vector<int>v4(v3);
printVactor(v4);
}
int main() {
test01();
system("pause");
return 0;
}
总结:vector 的多种构造方式没有可比性,灵活使用即可
功能描述:
- 给 vector 容器进行赋值
函数原型:
- vector& operator=(const vector &vec);//重载等号操作符
- assign(beg,end); //将[beg,end]区间中的数据拷贝赋值给本身
- assign(n,elem); //将 n 个 elem 拷贝赋值给本身
示例:
#include<iostream>
using namespace std;
#include<string>
#include <vector>
//vector赋值
void printVactor(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);
}
printVactor(v1);
//赋值 operator=
vector <int>v2;
v2=v1;
printVactor(v2);
// assign
vector<int> v3;
v3.assign(v1.begin(),v1.end());
printVactor(v3);
//n个elem方式赋值
vector<int> v4;
v4.assign(10,100);
printVactor(v4);
}
int main() {
test01();
system("pause");
return 0;
}
功能描述:
- 对 vector 容器的容量和大小操作
函数原型:
- empty(); //判断容器是否为空
- capacity(); //容器容量
- size();//放回容器中元素的个数
- resize(int num);//重新制定容器的长度为 num,若容器编程,则以默认值填充新位置。如果容器变短,则末尾超出容器长度的元素被删除
- resize(int num,elem);//重新指定容器的长度为 num,若容器变长,则以 elem 值填充新位置。如果容器变短,则末尾超出容器长度的元素被删除
示例:
#include<iostream>
using namespace std;
#include<string>
#include <vector>
//vector容量和大小
void printVactor(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);
}
printVactor(v1);
if(v1.empty()) //为真 代表容器为空
{
cout<<"v1为空"<<endl;
}
else
{
cout<<"v1不为空"<<endl;
cout<<"v1的容量为:"<<v1.capacity()<<endl;
cout<<"v1的大小为:"<<v1.size()<<endl;
}
//重新指定大小
// v1.resize(15);
// printVactor(v1);
v1.resize(15,10);
printVactor(v1);
}
int main() {
test01();
system("pause");
return 0;
}
功能描述:
- 对 vector 容器进行插入,删除操作
函数原理:
- push_back(ele);//尾部插入元素 ele
- pop_back();//删除最后一个元素
- insert(const_iterator pos,ele);//迭代器指向位置 pos 插入 count 个元素 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();//删除容器中所有元素
示例:
#include<iostream>
using namespace std;
#include<string>
#include <vector>
//vector插入和删除
void printVactor(vector<int>&v)
{
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
vector<int>v1;
//尾插法
v1.push_back(10);
v1.push_back(20);
v1.push_back(30);
v1.push_back(40);
printVactor(v1);
//尾删
v1.pop_back();
printVactor(v1);
//插入 第一个参数是迭代器
v1.insert(v1.begin(),100);
printVactor(v1);
v1.insert(v1.begin(),2,1000);
printVactor(v1);
//删除 参数也是迭代器
v1.erase(v1.begin());
printVactor(v1);
v1.erase(v1.begin(),v1.end());
printVactor(v1);
//清空
v1.clear();
printVactor(v1);
}
int main() {
test01();
system("pause");
return 0;
}
总结:
- 尾插---push_back
- 尾删---pop_back
- 插入---insert (位置迭代器)
- 删除---erase (位置迭代器)
- 清空---clear
功能描述:
- 对 vector 中的数据的存取操作
函数原型:
- at(int idx);//返回索引 idx 所指的数据
- operator[];//返回容器中第一个数据元素
- front();//返回容器中第一个数据元素
- back();//返回容器中最后一个数据元素
示例:
#include<iostream>
using namespace std;
#include<string>
#include <vector>
//vector容器 数据存取
void test01()
{
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() {
test01();
system("pause");
return 0;
}#include<iostream>
using namespace std;
#include<string>
#include <vector>
//vector容器 数据存取
void test01()
{
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() {
test01();
system("pause");
return 0;
}
总结:
- 除了用迭代器获取 vector 容器中元素,[]和 at 也可以
- front 返回容器第一个元素
- back 返回容器最后一个元素
功能描述:
- 实现两个容器内元素进行互换
函数原型:
- swap(vec);//将 vec 与本身的元素互换
示例:
#include<iostream>
using namespace std;
#include <vector>
//vector容器 互换
void printVector(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);
}
cout<<"交换前:"<<endl;
printVector(v1);
vector<int> v2;
for (int j = 10; j >0 ; j--) {
v2.push_back(j);
}
printVector(v2);
cout<<"交换后:"<<endl;
v1.swap(v2);
printVector(v1);
printVector(v2);
}
//实际用途
//巧用swap可以收缩内存空间
void test02()
{
vector<int> v;
for (int i = 0; i <100000; 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).swap(v);
cout<<"v的容量为:"<<v.capacity()<<endl;
cout<<"v的大小为:"<<v.size()<<endl;
}
int main() {
//test01();
test02();
system("pause");
return 0;
}
总结:swap 可以使用两个容器互换后,达到一种实用的收缩内存效果
功能描述:
- 减少 vector 在动态扩展容量时的扩展次数
函数原理:
- reserve(int len);//容器预留 len 个元素长度,预留位置不初始化,元素不可以访问
示例:
#include<iostream>
using namespace std;
#include <vector>
//vector容器 预留空间
void printVector(vector<int>& v)
{
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
vector<int>v1;
//利用reserve预留空间
v1.reserve(10000);
int num=0;//统计开辟次数
int * p=NULL;
for (int i = 0; i <100000 ; i++) {
v1.push_back(i);
if(p!=&v1[0])
{
p=&v1[0];
num++;
}
}
cout<<"num="<<num<<endl;
}
int main() {
test01();
system("pause");
return 0;
}
总结:如果数量较大 可以一开始利用 reserve 预留空间
功能:
- 双端数组,可以对头端进行插入删除操作
deque 与 vector 区别
- vector 对于头部的插入删除效率低,数据量越大,效率越低
- deque 相对而言,对头部的插入删除速度回比 vector 快
- vector 访问元素时的速度会比 deque 快,这和两者内部实现有关
deque 内部工作原理:
deque 内部有个中控器,维护每段缓冲区中的内容,缓冲区中存放真实数据
中控器维护的是每个缓冲区的地址,是的使用 deque 时像一片连续的内存空间
deque 容器的迭代器也是支持随机访问的
功能描述:
- deque 容器构造
函数原型:
- deque< T > deq; //默认构造形式
- deque(beg,end); //构造函数将[beg,end]区间中的元素拷贝给本身
- deque(n,elem);//构造函数将 n 个 elem 拷贝给本身
- deque(const deque &deq); //拷贝构造函数
示例:
#include<iostream>
using namespace std;
#include <deque>
//deque容器 预留空间
void printDeque(deque<int>& d)
{
for(deque<int>::const_iterator it=d.begin();it!=d.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
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);
}
int main() {
test01();
system("pause");
return 0;
}
总结:deque 容器和 vector 容器的构造方式几乎一致,灵活使用即可
功能描述:
- 给 deque 容器进行赋值
函数原型:
- deque& operator=const deque &deq;//重载等号操作符
- assign(beg,end);//将[beg,end]区间中的数据拷贝赋值给本身
- assign(n,elem); //将 n 个 elem 拷贝赋值给本身
示例:
#include<iostream>
using namespace std;
#include <deque>
//deque容器 赋值操作
void printDeque(const deque<int>& d)
{
for(deque<int>::const_iterator it=d.begin();it!=d.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
deque<int> d1;
for (int i = 0; i <10; i++) {
d1.push_back(i);
}
printDeque(d1);
//operator=赋值
deque<int>d2;
d2=d1;
printDeque(d2);
//assign赋值
deque<int>d3;
d3.assign(d1.begin(),d1.end());
printDeque(d3);
deque<int> d4;
d4.assign(10,100);
printDeque(d4);
}
int main() {
test01();
system("pause");
return 0;
}
功能描述:
- 对 deque 容器的大小进行操作
函数原型:
- deque.empty(); //判断容器是否为空
- deque.size();//返回容器中元素的个数
- deque.resize(num);//重新指定容器的长度为 num,若容器变长,则以默认值填充新位置。如果容器变短,则末尾超出容器长度的元素被删除
- deque.resize(num,elem);//重新指定容器的长度为 num,r 若容器变长,则以 elem 值填充新位置,如果容器变短,则末尾超出容器长度的元素被删除。
示例:
#include<iostream>
using namespace std;
#include <deque>
//deque容器 大小操作
void printDeque(const deque<int>& d)
{
for(deque<int>::const_iterator it=d.begin();it!=d.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
deque<int> d1;
for (int i = 0; i <10; i++) {
d1.push_back(i);
}
printDeque(d1);
if(d1.empty())
{
cout<<"d1为空"<<endl;
}
else
{
cout<<"d1不为空"<<endl;
cout<<"d1的大小为:"<<d1.size()<<endl;
//deque容器没有容器概念
}
d1.resize(15);
printDeque(d1);
}
int main() {
test01();
system("pause");
return 0;
}
总结:
- deque 没有容量的概念
- 判断是否为空 ---empty
- 返回元素个数 ---size
- 重新指定个数 ---resize
功能描述:
- 向 deque 容器中插入和删除数据
函数原型:
两端插入操作:
- push_back(elem);//在容器尾部添加一个数据
- push_front(elem);//在容器头部插入一个数据
- pop_back();//删除容器最后一个数据
- 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 位置的数据,返回下一个数据的位置
#include<iostream>
using namespace std;
#include <deque>
//deque容器 大小操作
void printDeque(const deque<int>& d)
{
for(deque<int>::const_iterator it=d.begin();it!=d.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
deque<int> d1;
//尾插
d1.push_back(10);
d1.push_back(20);
//头插
d1.push_front(100);
d1.push_front(200);
printDeque(d1);
//尾删
d1.pop_back();
printDeque(d1);
//头删
d1.pop_front();
printDeque(d1);
}
void test02()
{
deque<int> d1;
d1.push_back(10);
d1.push_back(20);
d1.push_front(100);
d1.push_front(200);
printDeque(d1);
//insert插入
d1.insert(d1.begin(),1000);
printDeque(d1);
d1.insert(d1.begin(),2,10000);
printDeque(d1);
//按照区间进行插入
deque<int> d2;
d2.push_back(1);
d2.push_back(2);
d2.push_back(3);
d1.insert(d1.begin(),d2.begin(),d2.end());
printDeque(d1);
}
void test03()
{
deque<int> d1;
d1.push_back(10);
d1.push_back(20);
d1.push_front(100);
d1.push_front(200);
deque<int>::iterator it=d1.begin();
it++;
d1.erase(it);
printDeque(d1);
d1.erase(d1.begin());
printDeque(d1);
d1.erase(d1.begin(),d1.end());
printDeque(d1);
}
int main() {
test03();
system("pause");
return 0;
}
总结:
- 插入和删除提供位置是迭代器
- 尾插---push_back
- 尾删---pop_back
- 头插---push_front
- 头删---pop_front
功能描述:
- 对 deque 中的数据的存取操作
函数原型:
- at(int idx);//返回索引 idx 所指的数据
- operator[];//返回索引 idx 所指的数据
- front();//返回容器中第一个数据元素
- back();//返回容器中最后一个数据元素
#include<iostream>
using namespace std;
#include <deque>
void test01()
{
deque<int> d1;
//尾插
d1.push_back(10);
d1.push_back(20);
d1.push_back(30);
//头插
d1.push_front(100);
d1.push_front(200);
d1.push_front(300);
//通过[]方式访问元素
for (int i = 0; i <d1.size() ; i++) {
cout<<d1[i]<<" ";
}
cout<<endl;
//通过at方式访问元素
for (int j = 0; j <d1.size() ; j++) {
cout<<d1.at(j)<<" ";
}
cout<<endl;
cout<<"第一个元素为:"<<d1.front()<<endl;
cout<<"最后一个元素:"<<d1.back()<<endl;
}
int main() {
test01();
system("pause");
return 0;
}
总结:
- 除了用迭代器获取 deque 容器中元素,[]和 at 也可以
- front 返回容器第一个元素
- back 返回容器最后一个元素
功能描述:
- 利用算法实现对 deque 容器进行排序
算法:
- sort(iterator beg,iterator end);//对 beg 和 end 区间内元素进行排序
示例:
#include<iostream>
using namespace std;
#include <deque>
#include <algorithm> //标准算法头文件
void printDeque(const deque<int>&d)
{
for(deque<int>::const_iterator it=d.begin();it!=d.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
deque<int> d1;
//尾插
d1.push_back(10);
d1.push_back(20);
d1.push_back(30);
//头插
d1.push_front(100);
d1.push_front(200);
d1.push_front(300);
printDeque(d1);
//排序 默认排序规则 从小到大 升序
//对于支持随机访问的迭代器的容器,都可以利用sort算法直接对其进行排序
//vector容器也可以利用sort进行排序
sort(d1.begin(),d1.end());
cout<<"排序后:"<<endl;
printDeque(d1);
}
int main() {
test01();
system("pause");
return 0;
}
总结:sort 算法非常实用,使用是包含头文件 algorithm 即可
有 5 名选手:选手 ABCDE,10 个评委分别对每一名选手打分,去除最高分,去除评委中最低分,取平均分。
1.创建五名选手,放到 vector 中
2.遍历 vector 容器,取出来每一个选手,执行 for 循环,可以把 10 个评分打分存到 deque 容器中
3.sort 算法对 deque 容器找那个分数排序,去除最高分和最低分
4.deque 容器遍历一遍,累加总分
5.获取平均分
代码:
#include<iostream>
using namespace std;
#include <deque>
#include <algorithm> //标准算法头文件
#include <vector>
#include <string>
#include <ctime>
class Person
{
public:
Person(string name,int score)
{
this->m_Name=name;
this->m_Score=score;
}
string m_Name;
int m_Score;
};
void createPerson(vector<Person>&v)
{
string nameSeed="ABCDE";
for(int i=0;i<5;i++)
{
string name="选手";
name+=nameSeed[i];
int score=0;
Person p(name,score);
//将创建的person对象 放入到容器中
v.push_back(p);
}
}
//打分
void setScore(vector<Person>&v)
{
for(vector<Person>::iterator it=v.begin();it!=v.end();it++)
{
//将评委分数 防暑到deque容器中
deque<int> d;
for(int i=0;i<10;i++)
{
int score=rand()%41+60; //60~100
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<Person>&v)
{
for(vector<Person>::iterator it=v.begin();it!=v.end();it++)
{
cout<<"姓名:"<<it->m_Name<<" 平均分:"<<it->m_Score<<endl;
}
}
int main() {
//随机数种子
srand((unsigned int)time(NULL));
//1.创建5名选手
vector<Person> v;
createPerson(v);
//2.给5名选手打分
setScore(v);
//3.显示最后得分
showScore(v);
system("pause");
return 0;
}
概念:stack 是一种先进后出(First In Last Out,FILO)的数据结构,他只有一个出口
栈中只有顶端的元素才可以被外界使用,因此栈不允许有遍历行为
栈中进入数据称为---入栈 push
栈中弹出数据称为---出栈 pop
功能描述:栈容器常用的对外接口
构造函数:
- stack< T > stk; //stack 采用模板类实现,stack 对象的默认构造形式
- stack(const stack &stk); //拷贝构造函数
赋值操作:
- stack& operator=(const stack &stk); //重载等号操作符
数据存取:
- push(elem); //向栈顶添加元素
- pop(); //从栈顶移除第一个元素
- top(); //返回栈顶元素
大小操作:
- empty() //判断堆栈是否为空
- size(); //返回栈的大小
#include<iostream>
using namespace std;
#include <stack>
//栈stack容器
void test01()
{
//特点:符合先进后出数据结构
stack<int> s;
//入栈
s.push(10);
s.push(20);
s.push(30);
s.push(40);
cout<<"栈的大小:"<<s.size()<<endl;
//只要栈不为空,查看栈顶,并且执行出栈操作
while(!s.empty())
{
//查看栈顶元素
cout<<"栈顶元素为:"<<s.top()<<endl;
//出栈
s.pop();
}
cout<<"栈的大小:"<<s.size()<<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
总结:
- 入栈 ---push
- 出栈 ---pop
- 返回栈顶 ---top
- 判断栈是否为空 ---empty
- 返回栈大小 ---size
概念:Queue 是一种先进先出(First In First Out,FIFO)的数据结构,它有两个出口
队列容器允许从一端新增元素,从另一端移除元素
队列中只有对头和队尾才可以被外界使用,因此队列不允许有遍历行为
队列中进数据称为---入队 push
队列中出数据称为---出队 pop
功能描述:栈容器常用的对外接口
构造函数:
- queue< T > que; //queue 采用模板类实现,queue 对象的默认构造形式
- queue(const queue &que); //拷贝构造函数
赋值操作:
- queue& operator=(const queue &que); //重载等号操作符
数据存取:
- push(elem); //往队尾添加元素
- pop(); //从对头移除第一个元素
- back(); //返回最后一个元素
- front(); //返回第一个元素
大小操作:
- empty(); //判断堆栈是否为空
- size(); //返回栈的大小
#include<iostream>
using namespace std;
#include <queue>
#include <string>
//队列 queue
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("张三",23);
Person p2("李四",24);
Person p3("王五",25);
Person p4("赵六",26);
//入队
q.push(p1);
q.push(p2);
q.push(p3);
q.push(p4);
cout<<"队列大小为:"<<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<<"队列大小为:"<<q.size()<<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
总结:
- 入队 ---push
- 出队 ---pop
- 返回对头元素 ---front
- 返回队尾元素 ---back
- 判断队是否为空 ---empty
- 返回队列大小 ---size
功能:将数据进行链式存储
链表:list 是一种物理存储单元上非来旭的存储结构,数据元素的逻辑顺序是通过链表实现的
链表的组成:链表由一系列结点组成
结点的组成:一个时存储数据元素的数据域,另一个是存储下一个结点地址的指针域
STL 中的链表是一个双向循环链表
由于链表的存储方式并不是连续的内存空间,因此链表 list 中的迭代器只支持前移和后移,属于双向迭代器
list 优点:
- 采用动态存储分配,不会造成内存浪费和溢出
- 链表执行插入和删除操作十分方便,修改指针即可,不需要移动大量元素
list 的缺点:
- 链表灵活,但是空间(指针域)和时间(变量)额外耗费较大
list 有一个重要的性质,插入操作和删除操作都不会造成原有 list 迭代器的失效,这在 vector 是不成立的
总结:STL 中 List 和 vector 是两个最常被使用的容器,各有优缺点
功能描述:
- 创建 list 容器
函数原型:
- list< T > lst; //list 采用模板类实现,对象的默认构造形式
- list(beg,end);//构造函数将[beg,end]区间中的元素拷贝给本身
- list(n,elem);//构造函数将 n 个 elem 拷贝给本身
- list(const list &lst); //拷贝构造函数。
示例:
#include<iostream>
using namespace std;
#include<list>
void printList(const list<int>& l)
{
for(list<int>::const_iterator it=l.begin();it!=l.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
//list容器构造函数
void test01()
{
//创建list容器
list<int> l1;//默认构造
l1.push_back(10);
l1.push_back(20);
l1.push_back(30);
l1.push_back(40);
printList(l1);
//区间方式构造
list<int> l2(l1.begin(),l1.end());
printList(l2);
//拷贝构造
list<int>l3(l2);
printList(l3);
//n个elem
list<int> l4(10,1000);
printList(l4);
}
int main(){
test01();
system("pause");
return 0;
}
总结:list 构造方式同其他几个 STL 常用容器,熟悉掌握即可
功能描述:
- 给 list 容器进行赋值,以及交换 list 容器
函数原型:
- assign(beg,end); //将[beg,end]区间中的数据拷贝赋值给本身
- assign(n,elem);//将 n 个 elem 拷贝赋值给本身
- list& operator=(const list &lst); //重载符号操作符
- swap(lst); //将 lst 与本身的元素互换
示例:
#include<iostream>
using namespace std;
#include<list>
void printList(const list<int>& l)
{
for(list<int>::const_iterator it=l.begin();it!=l.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
//创建list容器
list<int> l1;
l1.push_back(10);
l1.push_back(20);
l1.push_back(30);
l1.push_back(40);
printList(l1);
list<int> l2;
l2=l1;
printList(l2);
list<int> l3;
l3.assign(l2.begin(),l2.end());
printList(l3);
list<int> l4;
l4.assign(10,100);
printList(l4);
}
//交换
void test02()
{
list<int> l1;
l1.push_back(10);
l1.push_back(20);
l1.push_back(30);
l1.push_back(40);
list<int> l2;
l2.assign(10,100);
cout<<"交换前:"<<endl;
printList(l1);
printList(l2);
l1.swap(l2);
cout<<"交换后"<<endl;
printList(l1);
printList(l2);
}
int main(){
test01();
test02();
system("pause");
return 0;
}
总结:list 赋值和交换操作能够灵活运用即可
功能描述:
- 对 list 容器的大小进行操作
函数原型:
- size(); //返回容器中元素的个数
- empty(); //判断容器是否为空
- resize(num);//重新指定容器的长度为 num,若容器变成,则以默认值填充新位置。如果容器变短,则末尾超出容器长度的元素被删除
- resize(num,elem);//重新指定容器的长度为 num,若容器变长,则以 elem 值填充新位置。如果容器变短,则末尾查出容器长度的元素被删除
#include<iostream>
using namespace std;
#include<list>
void printList(const list<int>& l)
{
for(list<int>::const_iterator it=l.begin();it!=l.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
//创建list容器
list<int> l1;
l1.push_back(10);
l1.push_back(20);
l1.push_back(30);
l1.push_back(40);
printList(l1);
//判断容器是否为空
if(l1.empty())
{
cout<<"l1为空"<<endl;
}
else
{
cout<<"l1不为空"<<endl;
cout<<"l1元素个数为:"<<l1.size()<<endl;
}
//重新指定大小
// l1.resize(10);
// printList(l1);
l1.resize(10,100);
printList(l1);
}
int main(){
test01();
system("pause");
return 0;
}
功能描述:
- 对 list 容器进行数据的插入和删除
函数原型:
- push_back(elem);//在容器尾部加入一个元素
- pop_back();//删除容器中最后一个元素
- push_front(elem);//在容器开头插入一个元素
- pop_front();//从容器开头移除第一个元素
- insert(pos,elem);//在 pos 位置插 elem 元素的拷贝,返回新数据的位置
- insert(pos,beg,end);//在 pos 位置插入[beg,end]区间的数据,无返回值。
- clear();//移除容器的所有数据
- erase(beg,end);//删除[beg,end]区间的数据,返回下一个数据的位置
- erase(pos);//删除 pos 位置的数据,返回一亿个数据的位置
- remove(elem);//删除容器中所有与 elem 值匹配的元素
#include<iostream>
using namespace std;
#include <list>
//deque容器 大小操作
void printDeque(const list<int>& d)
{
for(list<int>::const_iterator it=d.begin();it!=d.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
list<int> l1;
//尾插
l1.push_back(10);
l1.push_back(20);
//头插
l1.push_front(100);
l1.push_front(200);
printDeque(l1);
//尾删
l1.pop_back();
printDeque(l1);
//头删
l1.pop_front();
printDeque(l1);
}
void test02()
{
list<int> l1;
l1.push_back(10);
l1.push_back(20);
l1.push_front(100);
l1.push_front(200);
printDeque(l1);
//insert插入
l1.insert(l1.begin(),1000);
printDeque(l1);
l1.insert(l1.begin(),2,10000);
printDeque(l1);
//按照区间进行插入
list<int> l2;
l2.push_back(1);
l2.push_back(2);
l2.push_back(3);
l1.insert(l1.begin(),l2.begin(),l2.end());
printDeque(l1);
}
void test03()
{
list<int> l1;
l1.push_back(10);
l1.push_back(20);
l1.push_front(100);
l1.push_front(200);
list<int>::iterator it=l1.begin();
it++;
l1.erase(it);
printDeque(l1);
l1.erase(l1.begin());
printDeque(l1);
l1.erase(l1.begin(),l1.end());
printDeque(l1);
}
int main() {
test03();
system("pause");
return 0;
}
总结:
- 尾插 ---push_back
- 尾删 ---pop_back
- 头插 ---push_front
- 头删 ---pop_front
- 插入 ---insert
- 删除 ---erase
- 移除 ---remove
- 清空 ---clear
功能描述:
- 对 list 容器中数据进行存取
函数原型:
- front(); //返回第一个元素
- back(); //返回最后一个元素
#include<iostream>
using namespace std;
#include<list>
void printList(const list<int>& l)
{
for(list<int>::const_iterator it=l.begin();it!=l.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
//创建list容器
list<int> l1;
l1.push_back(10);
l1.push_back(20);
l1.push_back(30);
l1.push_back(40);
//l1[0] 不可以用[]访问list容器中的元素
//l1.at(0) 不可以用at方式访问list容器中的元素
//原因是list本质链表,不是用连续性空间存储数据,迭代器也是不支持随机访问的
cout<<"第一个元素为:"<<l1.front()<<endl;
cout<<"最后一个元素为:"<<l1.back()<<endl;
// printList(l1);
//验证迭代器是不支持随机访问的
list<int>::iterator it =l1.begin();
it++;//支持双向
it--;
// it=it+1; //不支持随机访问
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- list 容器中不可以通过[]或者 at 方式访问数据
- 返回第一个元素 ---front
- 返回最后一个元素 ---back
功能描述:
- 将容器中的元素反转,以及将容器中的数据进行排序
函数原型:
- reverse();//反转链表
- sort(); //链表排序
示例:
#include<iostream>
using namespace std;
#include<list>
void printList(const list<int>& l)
{
for(list<int>::const_iterator it=l.begin();it!=l.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
bool myCompare(int v1,int v2)
{
return v1>v2;
}
void test01()
{
//创建list容器
list<int> l1;
l1.push_back(30);
l1.push_back(10);
l1.push_back(20);
l1.push_back(50);
l1.push_back(40);
cout<<"反转前:"<<endl;
printList(l1);
//反转
l1.reverse();
cout<<"反转后:"<<endl;
printList(l1);
//排序
cout<<"排序前:"<<endl;
printList(l1);
//反转
//所有不支持随机访问迭代器的容器,不可以用标准算法
//不支持随机访问迭代器的容器,内部会提供对应一些算法
// sort(l1.begin(),l1.end());
l1.sort();
cout<<"排序后:"<<endl;
printList(l1);
l1.sort(myCompare);
printList(l1);
}
int main(){
test01();
system("pause");
return 0;
}
3.7.8 排序案例
案例描述:将 Person 自定义数据类型进行排序,Person 中属性有姓名、年龄、身高。
排序规则:按照年龄进行升序排序,如果年龄相同按照身高进行降序
代码:
#include<iostream>
using namespace std;
#include<list>
#include <string>
class Person{
public:
Person(string name,int age,int height)
{
this->m_Name=name;
this->m_Age=age;
this->m_Height=height;
}
string m_Name;
int m_Age;
int m_Height;
};
bool comparePerson(Person &p1,Person &p2)
{
//如果年龄相同 按身高排序
if(p1.m_Age==p2.m_Age)
{
return p1.m_Height>p2.m_Height;
}
//按年龄 升序
return p1.m_Age<p2.m_Age;
}
void test01()
{
list<Person> list1;
Person p1("刘备",35,175);
Person p2("孙权",30,165);
Person p3("曹操",35,170);
Person p4("关羽",34,195);
Person p5("刘备",33,185);
//插入数据
list1.push_back(p1);
list1.push_back(p2);
list1.push_back(p3);
list1.push_back(p4);
list1.push_back(p5);
cout<<"排序前:"<<endl;
for(list<Person>::iterator it=list1.begin();it!=list1.end();it++)
{
cout<<"姓名:"<<(*it).m_Name<<" 年龄:"<<it->m_Age<<" 身高:"<<it->m_Height<<endl;
}
//排序
cout<<"---------------------------------"<<endl;
cout<<"排序后:"<<endl;
list1.sort(comparePerson);
for(list<Person>::iterator it=list1.begin();it!=list1.end();it++)
{
cout<<"姓名:"<<(*it).m_Name<<" 年龄:"<<it->m_Age<<" 身高:"<<it->m_Height<<endl;
}
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- 对于自定义数据类型,必须要指定排序规则,否则编译器不知道如何进行排序
- 高级排序只是在排序规则上在进行一次逻辑规则制定,并不复杂
简介:
- 所有元素都会在插入时自动被排序
本质:
- set/multiset 属于关联式容器,底层结构是用二叉树实现
set 和 multiset 区别:
- set 不允许容器中有重复的元素
- multiset 允许容器中有重复的元素
功能描述:创建 set 容器以及赋值
构造:
- set< T > st; //默认构造函数;
- set(const set &st); //拷贝构造函数
赋值:
- set& operator=(const set &st); //重载等号操作符
示例:
#include<iostream>
using namespace std;
#include<set>
#include <string>
void printSet(set<int> & st)
{
for(set<int>::iterator it=st.begin();it!=st.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
set<int> st1;
//插入数据 只有insert方式
st1.insert(10);
st1.insert(20);
st1.insert(30);
st1.insert(40);
//set容器特点:所有元素插入时候自动被排序
//set容器不允许插入重复值
printSet(st1);
//拷贝构造
set<int> st2(st1);
printSet(st2);
//赋值
set<int>st3;
st3=st2;
printSet(st3);
}
int main(){
test01();
system("pause");
return 0;
}
功能描述:
- 统计 set 容器大小以及交换 set 容器
函数原型:
- size(); //返回容器中元素的数目
- empty(); //判断容器是否为空
- swap(st); //交换两个集合容器
#include<iostream>
using namespace std;
#include<set>
#include <string>
void printSet(set<int> & st)
{
for(set<int>::iterator it=st.begin();it!=st.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
set<int> st1;
//插入数据 只有insert方式
st1.insert(10);
st1.insert(20);
st1.insert(30);
st1.insert(40);
//判断是否为空
if(st1.empty())
{
cout<<"st1为空"<<endl;
}
else
{
cout<<"st1不为空"<<endl;
cout<<"st1的大小为:"<<st1.size()<<endl;
}
set<int> st2;
//插入数据 只有insert方式
st2.insert(100);
st2.insert(200);
st2.insert(300);
st2.insert(400);
cout<<"交换前:"<<endl;
printSet(st2);
cout<<"交换后:"<<endl;
st1.swap(st2);
printSet(st2);
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- 统计大小 --- size
- 判断是否为空 ---empty
- 交换容器 ---swap
功能描述:
- set 容器进行插入数据和删除数据
函数原型:
- insert(elem); //在容器中插入元素
- clear(); //清除所有元素
- erase(pos); //删除 pos 迭代器所指的元素,返回下一个元素的迭代器
- earse(beg,end);//删除区间[beg,end]的所有元素,返回下一个元素的迭代器,
- erase(elem); //删除容器中值为 elem 的元素
示例:
#include<iostream>
using namespace std;
#include<set>
#include <string>
void printSet(set<int> & st)
{
for(set<int>::iterator it=st.begin();it!=st.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
set<int> st1;
//插入数据 只有insert方式
st1.insert(20);
st1.insert(10);
st1.insert(30);
st1.insert(40);
printSet(st1);
//删除
st1.erase(st1.begin());
printSet(st1);
//删除重载版本
st1.erase(30);
printSet(st1);
//清空
st1.erase(st1.begin(),st1.end());
st1.clear();
printSet(st1);
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- 插入 ---insert
- 删除 ---erase
- 清空 ---clear
功能描述:
- 对 set 容器进行查找数据以及统计数据
函数原型:
- find(key); //查找 key 是否存在,若存在,返回该键的元素的迭代器;若不存在返回 set.end();
- count(key); //统计 key 的元素个数
示例:
#include<iostream>
using namespace std;
#include<set>
#include <string>
void printSet(set<int> & st)
{
for(set<int>::iterator it=st.begin();it!=st.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void test01()
{
set<int> st1;
//插入数据 只有insert方式
st1.insert(10);
st1.insert(20);
st1.insert(30);
st1.insert(40);
set<int>::iterator pos=st1.find(30);
if(pos!=st1.end())
{
cout<<"找到元素:"<<*pos<<endl;
}
else
{
cout<<"未找到元素"<<endl;
}
}
void test02()
{
set<int> st1;
//插入数据 只有insert方式
st1.insert(10);
st1.insert(20);
st1.insert(30);
st1.insert(40);
st1.insert(30);
st1.insert(30);
int num=st1.count(30);
//对于set而言 统计结果 要么是0 要么为1
cout<<"num="<<num<<endl;
}
int main(){
test02();
system("pause");
return 0;
}
3.8.6 set 和 multiset 区别
学习 mubiao:
- 掌握 set 和 multiset 的区别
区别:
- set 不可以插入重复数据,而 multiset 可以
- set 插入数据的同时会返回插入结果,表示插入是否成功
- multiset 不会检测数据,因此可以插入重复数据
示例:
#include<iostream>
using namespace std;
#include<set>
#include <string>
void test01()
{
set<int> s;
pair<set<int>::iterator,bool> ret=s.insert(10);
if(ret.second)
{
cout<<"第一次插入成功"<<endl;
}
else
{
cout<<"第一次插入失败"<<endl;
}
ret=s.insert(10);
if(ret.second)
{
cout<<"第二次插入成功"<<endl;
}
else
{
cout<<"第二次插入失败"<<endl;
}
multiset<int> ms;
//允许插入重复值
ms.insert(10);
ms.insert(10);
for (multiset<int>::iterator it=ms.begin();it!=ms.end();it++) {
cout<<*it<<" ";
}
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- 如果不允许插入重复数据可以利用 set
- 如果需要插入重复数据利用 multiset
功能描述:
- 成对出现的数据,利用对组可以返回两个数据
两种创建方式:
- pair< type ,type> p(value1,value2);
- pair< type,type > p=make_pair(value1,value2);
示例:
#include<iostream>
using namespace std;
#include<set>
#include <string>
void test01()
{
pair<string,int> p(string("Tom"),20);
cout<<"姓名:"<<p.first<<" 年龄:"<<p.second<<endl;
pair<string,int> p2=make_pair("Jerry",10);
cout<<"姓名:"<<p.first<<" 年龄:"<<p.second<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
学习目标:
- set 容器默认排序规则为从小到大,掌握如何改变排序规则
主要技术点:
- 利用仿函数,可以改变排序规则
示例一 set 存放内置数据类型
#include<iostream>
using namespace std;
#include<set>
#include <string>
class MyCompare
{
public:
bool operator()(int v1,int v2){
return v1>v2;
}
};
void test01()
{
set<int> s1;
s1.insert(10);
s1.insert(40);
s1.insert(20);
s1.insert(50);
s1.insert(30);
for(set<int>::iterator it=s1.begin();it!=s1.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
//指定排序规则为从到小
set<int,MyCompare> s2;
s2.insert(10);
s2.insert(40);
s2.insert(20);
s2.insert(50);
s2.insert(30);
for(set<int,MyCompare>::iterator it=s2.begin();it!=s2.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
示例二 set 存放自定义数据类型
#include<iostream>
using namespace std;
#include<set>
#include <string>
class Person
{
public:
Person(string name,int age)
{
this->m_Name=name;
this->m_Age=age;
}
string m_Name;
int m_Age;
};
class comparePerson
{
public:
bool operator()(const Person& p1,const Person&p2){
//按照年龄 降序
return p1.m_Age>p2.m_Age;
}
};
void test01()
{
set<Person,comparePerson> s;
//创建数据
Person p1("刘备",22);
Person p2("关羽",21);
Person p3("张飞",20);
Person p4("曹操",25);
Person p5("孙权",19);
s.insert(p1);
s.insert(p2);
s.insert(p3);
s.insert(p4);
s.insert(p5);
for(set<Person,comparePerson>::const_iterator it=s.begin();it!=s.end();it++)
{
cout<<"姓名:"<<it->m_Name<<" 年龄:"<<it->m_Age<<endl;
}
}
int main(){
test01();
system("pause");
return 0;
}
总结:
对于自定义数据类型,set 必须指定排序规则才可以插入数据
简介:
- map 中所有元素都是 pair
- pair 中第一个元素为 key(键值),起到索引作用,第二个元素为 value(实值)
- 所有元素都会根据元素的键值自动排序
本质:
- map/multimap 属于关联式容器,底层结构是用二叉树实现
优点:
- 可以根据 key 值快速找到 value 值
map 和 multimap 区别:
- map 不允许容器中有重复 key 值元素
- multimap 允许容器中有重复的 key 值元素
功能描述:
- 对 map 容器进行构造和赋值操作
函数原型:
构造:
- map< T1, T2 > mp; //map 默认构造函数
- map(const map &mp); //拷贝构造函数
赋值:
- map& operator=(const map &mp);//重载等号操作符
示例:
#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;
}
}
void test01()
{
//创建map容器
map<int,int> mp1;
mp1.insert(pair<int,int>(1,10));
mp1.insert(pair<int,int>(2,20));
mp1.insert(pair<int,int>(3,30));
mp1.insert(pair<int,int>(4,40));
printMap(mp1);
//拷贝构造
map<int,int>mp2(mp1);
printMap(mp2);
//赋值
map<int,int>mp3;
mp3=mp2;
printMap(mp3);
}
int main(){
test01();
system("pause");
return 0;
}
总结:map 中所有元素都是成对出现,插入数据时候要使用对组
功能描述:
- 统计 map 容器大小以及交换 map 容器
函数原型:
- size();//返回容器中元素的数目
- empty();//判断容器是否为空
- swap(st);//交换两个集合容器
示例:
#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容器
map<int,int> mp1;
mp1.insert(pair<int,int>(1,10));
mp1.insert(pair<int,int>(2,20));
mp1.insert(pair<int,int>(3,30));
mp1.insert(pair<int,int>(4,40));
if(mp1.empty())
{
cout<<"mp1为空"<<endl;
}
else
{
cout<<"mp1不为空"<<endl;
cout<<"mp1的大小为:"<<mp1.size()<<endl;
}
}
//交换
void test02()
{
map<int,int> mp1;
mp1.insert(pair<int,int>(1,10));
mp1.insert(pair<int,int>(2,20));
mp1.insert(pair<int,int>(3,30));
mp1.insert(pair<int,int>(4,40));
map<int,int> mp2;
mp2.insert(pair<int,int>(4,100));
mp2.insert(pair<int,int>(5,200));
mp2.insert(pair<int,int>(6,300));
mp2.insert(pair<int,int>(7,400));
cout<<"交换前:"<<endl;
printMap(mp1);
printMap(mp2);
cout<<"交换后"<<endl;
mp1.swap(mp2);
printMap(mp1);
printMap(mp2);
}
int main(){
test02();
system("pause");
return 0;
}
总结:
- 统计大小 --size
- 判断是否为空 --empty
- 交换容器 --swap
功能描述:
- map 容器进行插入数据和删除数据
函数原型:
- insert(elem);//在容器中插入元素
- clear(); //清除所有元素
- erase(pos);//删除 pos 迭代器所指的元素,返回写一个元素的迭代器
- erase(beg,end);//删除区间[beg,end]的所有元素,返回下一个元素的迭代器
- erase(key);//删除容器中值为 key 的元素
#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容器
map<int,int> mp1;
//插入
//第一种
mp1.insert(pair<int,int>(1,10));
//第二种
mp1.insert(make_pair(2,20));
//第三种
mp1.insert(map<int,int>::value_type(3,30));
//第四种
mp1[4]=40;
//[]不建议插入,用途 可以利用key访问到value值
//cout<<mp1[4]<<endl;
printMap(mp1);
//删除
mp1.erase(mp1.begin());
printMap(mp1);
//按照key删除
mp1.erase(3);
printMap(mp1);
mp1.erase(mp1.begin(),mp1.end());
printMap(mp1);
mp1.clear();
printMap(mp1);
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- map 插入方式很多,记住其一即可
- 插入---insert
- 删除---erase
- 清空---clear
功能描述:
- 对 map 容器进行查找数据以及统计数据
函数原型:
- find(key);//查找 key 是否存在,若存在,返回该键的元素的迭代器;若不存在,返回 set.end();
- count(key); //统计 key 的元素个数
示例:
#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>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>(3,40));
//查找
map<int,int>::iterator pos=m.find(3);
if(pos!=m.end())
{
cout<<"查找到了元素key="<<pos->first<<"value="<<pos->second<<endl;
}
else
{
cout<<"未找到元素"<<endl;
}
//统计
//map不允许插入重复key 元素,count统计而言结果要么是0.要么是1
//multmap的count统计可能大于1
int num=m.count(3);
cout<<"num="<<num<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- 查找 ---find(返回的是迭代器)
- 统计 ---count(对于 map,结果为 0 或者 1)
学习目标:
- map 容器默认排序规则为 按照 key 值进行 从小到大排序,掌握如何改变排序规则
主要技术点:
- 利用仿函数,可以改变排序规则
示例:
#include<iostream>
using namespace std;
#include<map>
class MyCompare{
public:
bool operator()(int v1,int v2){
return v1>v2;
}
};
void test01()
{
map<int,int,MyCompare>m;
m.insert(pair<int,int>(2,20));
m.insert(pair<int,int>(1,10));
m.insert(pair<int,int>(5,50));
m.insert(pair<int,int>(4,40));
m.insert(pair<int,int>(3,30));
for(map<int,int,MyCompare>::iterator it=m.begin();it!=m.end();it++)
{
cout<<"key="<<it->first<<"value="<<it->second<<endl;
}
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- 利用仿函数可以指定 map 容器的排序规则
- 对于自定义数据类型,map 必须要指定排序规则,同 set 容器
- 公司今天招聘了 10 个员工(ABCDEFGHIJ),10 名员工进入公司之后,需要指派员工在哪个部门工作
- 员工信息有:姓名 工资组成;部门分为策划、美术、研发
- 随机给 10 名员工分配部分和工资
- 通过 multimap 进行信息的插入 key(部分编号) value(员工)
- 分部分显示员工信息
- 创建 10 名员工,放到 vector 中
- 遍历 vector 容器,取出每个员工,进行随机分组
- 分组后,将员工部门编号作为 key,具体员工作为 value,放入到 multimap 容器中
- 分部门显示员工信息
代码:
#include<iostream>
using namespace std;
#include<map>
#include <vector>
#include <string>
#include <ctime>
#define CEHUA 0
#define MEISHU 1
#define YANFA 2
//员工类
class Worker
{
public:
string m_Name;
int m_Salary;
};
//创建员工
void createWorker(vector<Worker>&v)
{
string namespeed="ABCDEFGHIJ";
for(int i=0;i<10;i++)
{
Worker worker;
worker.m_Name="员工";
worker.m_Name+=namespeed[i];
worker.m_Salary=rand()%10000+10000;
//将员工放入到vector容器中
v.push_back(worker);
}
}
//员工分组
void setGroup(vector<Worker>&v,multimap<int,Worker>&m)
{
for(vector<Worker>::iterator it=v.begin();it!=v.end();it++)
{
//产生随机部门编号
int deptId=rand()%3;
//将员工插入到分组中
//key部门编号,value具体员工
m.insert(make_pair(deptId,*it));
}
}
//分组显示员工
void showWorkerByGroup(multimap<int,Worker>&m)
{
cout<<"策划部门:"<<endl;
multimap<int,Worker>::iterator pos=m.find(CEHUA);
int count=m.count(CEHUA);//统计具体人数
int index=0;
for(;pos!=m.end() && index<count;pos++,index++)
{
cout<<"姓名:"<<pos->second.m_Name<<"工资:"<<pos->second.m_Salary<<endl;
}
cout<<"美术部门:"<<endl;
pos=m.find(MEISHU);
count=m.count(MEISHU);//统计具体人数
index=0;
for(;pos!=m.end() && index<count;pos++,index++)
{
cout<<"姓名:"<<pos->second.m_Name<<"工资:"<<pos->second.m_Salary<<endl;
}
cout<<"研发部门:"<<endl;
pos=m.find(YANFA);
count=m.count(YANFA);//统计具体人数
index=0;
for(;pos!=m.end() && index<count;pos++,index++)
{
cout<<"姓名:"<<pos->second.m_Name<<"工资:"<<pos->second.m_Salary<<endl;
}
}
int main(){
//随机数种子
srand((unsigned int)time(NULL));
//创建员工
vector<Worker>vWorker;
createWorker(vWorker);
//员工分组
multimap<int,Worker>mWorker;
setGroup(vWorker,mWorker);
//分组显示员工
showWorkerByGroup(mWorker);
//测试
//for(vector<Worker>::iterator it=vWorker.begin();it!=vWorker.end();it++)
//{
// cout<<"姓名:"<<it->m_Name<<"工资:"<<it->m_Salary<<endl;
//}
system("pause");
return 0;
}
概念:
- 重载函数调用操作符的类,其对象称为函数对象
- 函数对象使用重载的()时,行为类似函数调用,也叫仿函数
本质:
函数对象(仿函数)是一个类,不是一个函数
特点:
- 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
- 函数对象超出普通函数的概念,函数对象可以有自己的状态
- 函数对象可以作为参数传递
#include<iostream>
using namespace std;
#include <string>
class MyAdd
{
public:
int operator()(int v1,int v2)
{
return v1+v2;
}
};
class MyPrint
{
public:
MyPrint()
{
this->count=0;
}
void operator()(string test)
{
cout<<test<<endl;
this->count++;
}
int count; //内部自己状态
};
//函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
void test01()
{
MyAdd myAdd;
cout<<myAdd(10,10)<<endl;
}
//函数对象超出普通函数的概念,函数对象可以有自己的状态
void test02(){
MyPrint myPrint;
myPrint("hello world");
myPrint("hello world");
myPrint("hello world");
myPrint("hello world");
cout<<"MyPring调用次数为:"<<myPrint.count<<endl;
}
//函数对象可以作为参数传递
void doPrint(MyPrint & mp,string test)
{
mp(test);
}
void test03(){
MyPrint myPrint;
doPrint(myPrint,"Hello tfl");
}
int main(){
// test01();
// test02();
test03();
system("pause");
return 0;
}
总结:
- 仿函数写法非常灵活,可以作为参数进行传递
概念:
- 返回 bool 类型的仿函数称为谓词
- 如果 operator()接受一个参数,那么叫做一元谓词
- 如果 operator()接受两个参数,那么叫做二元谓词
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//仿函数 返回值类型是bool数据类型,称为谓词
//一元谓词
class GreaterFive
{
public:
bool operator()(int val)
{
return val>5;
}
};
void test01()
{
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
//查找容器中 有没有大于5的数字
//greaterfive()匿名函数对象
vector<int>::iterator it=find_if(v.begin(),v.end(),GreaterFive());
if(it==v.end())
{
cout<<"未找到"<<endl;
}
else
{
cout<<"找到了大于5的数字为:"<<*it<<endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
总结:参数只有一个的谓词,称为一元谓词
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//二元谓词
class MyCompare
{
public:
bool operator()(int val1,int val2)
{
return val1>val2;
}
};
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(40);
v.push_back(20);
v.push_back(30);
v.push_back(50);
sort(v.begin(),v.end());
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
//使用函数对象 改变算法策略,变为排序规则为从大到小
sort(v.begin(),v.end(),MyCompare());
cout<<"------------------------"<<endl;
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:参数只有两个的谓词,称为二元谓词
概念:
- STL 内建了一些函数对象
分类:
- 算术仿函数
- 关系仿函数
- 逻辑仿函数
用法:
- 这些仿函数所产生的的对象,用法和一般函数完全相同
- 使用内建函数对象,需要引入头文件#include< functional >
功能描述:
- 实现四则运算
- 其中 negate 是一元运算,其他都是二元运算
仿函数原型:
- template< class T > T plus< T > //加法仿函数
- template< class T > T minus< T > //减法仿函数
- template< class T > T multiplies< T > //乘法仿函数
- template< class T > T divides< T > //除法仿函数
- template< class T > T modulus< T > //取模仿函数
- template< class T > T negate< T > //取反仿函数
示例:
#include<iostream>
using namespace std;
#include <functional>
//内建函数对象 算术仿函数
//negate 一元仿函数 取反仿函数
void test01()
{
negate<int>n;
cout<<n(50)<<endl;
}
//plus 二元仿函数 加法
void test02(){
plus<int>p;
cout<<"和为:"<<p(10,20)<<endl;
}
//minus 二元仿函数 减法
void test03(){
minus<int>m;
cout<<"差为:"<<m(30,20)<<endl;
}
//multiplies 二元仿函数 乘法
void test04(){
multiplies<int>m;
cout<<"积为:"<<m(30,20)<<endl;
}
//divides 二元仿函数 除法
void test05(){
divides<int>d;
cout<<"商为:"<<d(30,6)<<endl;
}
//modulus 二元仿函数 取模
void test06(){
modulus<int>m;
cout<<"模为:"<<m(40,6)<<endl;
}
int main(){
test01();
test02();
test03();
test04();
test05();
test06();
system("pause");
return 0;
}
功能描述:
- 实现关系对比
仿函数原型:
函数表达式 | 关系 |
---|---|
template< class T> bool equal_to< T > | 等于 |
template< class T> bool not_equal_to< T > | 不等于 |
template< class T> bool greater< T > | 大于 |
template< class T> bool greater_equal< T > | 大于等于 |
template< class T> bool less< T > | 小于 |
template< class T> bool less_equal< T > | 小于等于 |
示例:
#include<iostream>
using namespace std;
#include <functional>
#include <vector>
#include <algorithm>
//内建函数对象 关系仿函数
//大于
class MyCompare
{
public:
bool operator()(int val1,int val2)
{
return val1>val2;
}
};
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(40);
v.push_back(20);
v.push_back(50);
for (vector<int>::iterator it=v.begin();it!=v.end();it++) {
cout<<*it<<" ";
}
cout<<endl;
//降序
//sort(v.begin(),v.end(),MyCompare());
//大于
sort(v.begin(),v.end(),greater<int>());
cout<<"------------------------"<<endl;
for (vector<int>::iterator it=v.begin();it!=v.end();it++) {
cout<<*it<<" ";
}
cout<<endl;
sort(v.begin(),v.end(),less<int>());
cout<<"------------------------"<<endl;
for (vector<int>::iterator it=v.begin();it!=v.end();it++) {
cout<<*it<<" ";
}
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:关系仿函数中最常用的就是 greater<>大于
功能描述:
- 实现逻辑运算
函数原型:
函数原型 | 关系 |
---|---|
template< class T > bool logical_and< T > | 逻辑与 |
template< class T > bool logical_or< T > | 逻辑或 |
template< class T > bool logical_not< T > | 逻辑非 |
示例:
#include<iostream>
using namespace std;
#include <functional>
#include <vector>
#include <algorithm>
//内建函数对象 逻辑仿函数
void test01()
{
vector<bool> v;
v.push_back(true);
v.push_back(false);
v.push_back(true);
v.push_back(false);
for (vector<bool>::iterator it=v.begin();it!=v.end();it++) {
cout<<*it<<" ";
}
cout<<endl;
//利用逻辑非 将容器v搬运到容器v2中,并执行取反操作
vector<bool> v2;
v2.resize(v.size());
transform(v.begin(),v.end(),v2.begin(),logical_not<bool>());
for (vector<bool>::iterator it=v2.begin();it!=v2.end();it++) {
cout<<*it<<" ";
}
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:逻辑仿函数实际应用较少,了解即可
概述:
- 算法主要是由头文件< algorithm >< functional >< numberic >组成
- < algorithm >是所有 STL 头文件中最大的一个,范围涉及到比较、交换、查找、遍历操作、复制、修改等等
- < numberic >体积很小,只包括几个在序列上面进行简短数学运算的模板函数
- < functional >定义了一些模板类,用以声明函数对象
学习目标:
- 掌握常用的遍历算法
算法简介:
- for_each //遍历容器
- transform //搬运容器到另一个容器中
功能描述:
- 实现遍历容器
函数原型:
-
for_each(iterator bug,iterator end,_func);
//遍历算法,遍历容器元素
//beg 开始迭代器
//end 结束迭代器
//_func 函数或者函数对象
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
//常用遍历算法 for_each
//普通函数
void print01(int val)
{
cout<<val<<" ";
}
//仿函数
class print02
{
public:
void operator()(int val)
{
cout<<val<<" ";
}
};
void test01()
{
vector<int>v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
for_each(v.begin(),v.end(),print01);
cout<<endl;
for_each(v.begin(),v.end(),print02());
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:for_each 在实际开发中是最常用遍历算法,需要熟练掌握
功能描述:
- 搬运函数容器到另一个容器中
函数原型:
-
transform<iterator beg1,iterator end1,iterator beg2,_func>
//beg1 源容器开始迭代器
//end1 源容器结束迭代器
//beg2 目标容器开始迭代器
//_func 函数或者函数对象
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
//常用遍历算法 transform
class Transform
{
public:
int operator()(int v)
{
return v+100;
}
};
//仿函数 打印
class print{
public:
void operator()(int val)
{
cout<<val<<" ";
}
};
void test01()
{
vector<int>v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
//目标容器
vector<int> v2;
v2.resize(v.size());//目标容器需要提前开辟空间
transform(v.begin(),v.end(),v2.begin(),Transform());
for_each(v2.begin(),v2.end(),print());
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
学习目标:
- 掌握常用的查找算法
算法简介:
- find //查找元素
- find_if //按条件查找元素
- adjacent_find //查找相邻重复元素
- binary_search //二分查找法
- count //统计元素个数
- count_if //按条件统计元素个数
功能描述:
- 查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器 end()
函数原型:
-
find(iterator beg,iterator end,value);
//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
//beg 开始迭代器
//end 结束迭代器
//value 查找元素
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
#include <string>
//常用的查找算法 find
//查找 内置数据类型
void test01()
{
vector<int>v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
//查找容器中是否有5这个元素
vector<int>::iterator it=find(v.begin(),v.end(),50);
if(it==v.end())
{
cout<<"没有找到该元素"<<endl;
}
else
{
cout<<"找到了元素为:"<<*it<<endl;
}
}
//查找 自定义数据类型
class Person
{
public:
Person(string name,int age)
{
this->m_name=name;
this->m_age=age;
}
//重载 == 底层find知道如何对比person数据类型
bool operator==(const Person&p)
{
if(this->m_name==p.m_name&&this->m_age==p.m_age)
{
return true;
}
else
{
return false;
}
}
string m_name;
int m_age;
};
void test02()
{
vector<Person>v;
Person p1("aaa",10);
Person p2("bbb",20);
Person p3("ccc",30);
Person p4("ddd",40);
//放入容器中
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
Person pp("bbb",20);
vector<Person>::iterator it=find(v.begin(),v.end(),pp);
if(it==v.end())
{
cout<<"没有找到p2"<<endl;
}
else
{
cout<<"找到了 姓名:"<<it->m_name<<"年龄:"<<it->m_age<<endl;
}
}
int main(){
//test01();
test02();
system("pause");
return 0;
}
总结:利用 find 可以在容器中找指定的元素,返回值是迭代器
功能描述:
- 按条件查找元素
函数原型:
-
find_if(iterator beg,iterator end,_Pred);
//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器
//beg 开始迭代器
//end 结束迭代器
//_Pred 函数或者谓词(返回 bool 类型的仿函数)
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
#include <string>
//常用的查找算法 find_if
//查找 内置数据类型
class GreaterFive
{
public:
bool operator()(int val)
{
return val>5;
}
};
void test01()
{
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
//查找容器中是否有5这个元素
vector<int>::iterator it=find_if(v.begin(),v.end(),GreaterFive());
if(it==v.end())
{
cout<<"没有找到该元素"<<endl;
}
else
{
cout<<"找到了对5的数字为:"<<*it<<endl;
}
}
//查找 自定义数据类型
class Person
{
public:
Person(string name,int age)
{
this->m_name=name;
this->m_age=age;
}
//重载 == 底层find知道如何对比person数据类型
bool operator==(const Person&p)
{
if(this->m_name==p.m_name&&this->m_age==p.m_age)
{
return true;
}
else
{
return false;
}
}
string m_name;
int m_age;
};
class Greater20
{
public:
bool operator()(Person &p)
{
return p.m_age>20;
}
};
void test02()
{
vector<Person>v;
Person p1("aaa",10);
Person p2("bbb",20);
Person p3("ccc",30);
Person p4("ddd",40);
//放入容器中
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
//找出年龄大于20的人
vector<Person>::iterator it=find_if(v.begin(),v.end(),Greater20());
if(it==v.end())
{
cout<<"没有找到p2"<<endl;
}
else
{
cout<<"找到了 姓名:"<<it->m_name<<"年龄:"<<it->m_age<<endl;
}
}
int main(){
//test01();
test02();
system("pause");
return 0;
}
功能描述:
- 查找相邻重复元素
函数原型:
-
adjacent_find(iterator beg,iterator end);
//查找相邻重复元素,返回相邻元素的第一个位置的迭代器
//beg 开始迭代器
//end 结束迭代器
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
#include <string>
//常用的查找算法 adjacent_find
void test01()
{
vector<int> v;
v.push_back(0);
v.push_back(2);
v.push_back(0);
v.push_back(3);
v.push_back(1);
v.push_back(4);
//相邻的两个相同的数
v.push_back(3);
v.push_back(3);
vector<int>::iterator it=adjacent_find(v.begin(),v.end());
if(it==v.end())
{
cout<<"未找到相邻重复的元素"<<endl;
}
else
{
cout<<"找到相邻重复的元素:"<<*it<<endl;
}
}
int main(){
test01();
system("pause");
return 0;
}
总结:面试题中如果出现查找相邻重复元素,记得用 STL 中的 adjacent_find 算法
功能描述:
- 查找指定元素是否存在
函数原型:
-
bool binary_search(iterator beg,iterator end,value);
//查找指定元素,查到 返回 true 否则 false
//注意:在无序序列中不可用
//beg 开始迭代器
//end 结束迭代器
//value 查找的元素
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
#include <string>
//常用的查找算法 binary_search
void test01()
{
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
//v.push_back(2); 如果是无序序列,结果未知!
//查找容器中是否有9 元素
//注意:容器必须是有序的序列
//二分查找
bool ret=binary_search(v.begin(),v.end(),9);
if(ret)
{
cout<<"找到了元素"<<endl;
}
else
{
cout<<"未找到"<<endl;
}
}
int main(){
test01();
system("pause");
return 0;
}
总结:二分查找法查找效率很高,值得注意的是查找的容器中元素必须的有序序列
功能描述:
- 统计元素个数
函数原型:
-
count(iterator beg,iterator end, value);
//统计元素出现次数
//beg 开始迭代器
//end 结束迭代器
//value 统计的元素
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
#include <string>
//常用的查找算法 count
//统计内置数据类型
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(40);
v.push_back(30);
v.push_back(40);
v.push_back(20);
v.push_back(40);
int num=count(v.begin(),v.end(),40);
cout<<"40的元素个数为:"<<num<<endl;
}
//统计自定义数据类型
class Person
{
public:
Person(string name,int age)
{
this->m_Name=name;
this->m_Age=age;
}
bool operator==(const Person &p)
{
if(this->m_Age==p.m_Age)
{
return true;
}
else
{
return false;
}
}
string m_Name;
int m_Age;
};
void test02()
{
vector<Person> v;
Person p1("aaa",30);
Person p2("bbb",40);
Person p3("ccc",30);
Person p4("ddd",35);
Person p5("eee",25);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
Person p("fff",30);
int num=count(v.begin(),v.end(),p);
cout<<"和fff同岁的人员个数为:"<<num<<endl;
}
int main(){
test01();
test02();
system("pause");
return 0;
}
总结:统计自定义数据类型时候,需要配置重载 operator==
功能描述:
- 按条件统计元素个数
函数原型:
-
count_if(iterator beg,iterator end,_Pred);
//按条件统计元素出现次数
//beg 开始迭代器
//end 结束迭代器
//_Pred 谓词
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
#include <string>
//常用的查找算法 count_if
//统计内置数据类型
class Greater20
{
public:
bool operator()(int val)
{
return val>20;
}
};
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(40);
v.push_back(20);
v.push_back(40);
v.push_back(30);
int num=count_if(v.begin(),v.end(),Greater20());
cout<<"大于20的元素个数为:"<<num<<endl;
}
//统计自定义数据类型
class Person
{
public:
Person(string name,int age)
{
this->m_Name=name;
this->m_Age=age;
}
string m_Name;
int m_Age;
};
class AgeGreater20
{
public:
bool operator()(const Person &p)
{
return p.m_Age>30;
}
};
void test02()
{
vector<Person> v;
Person p1("刘备",35);
Person p2("关羽",35);
Person p3("张飞",35);
Person p4("赵云",30);
Person p5("曹操",40);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
//统计 大于20人员个数
int num=count_if(v.begin(),v.end(),AgeGreater20());
cout<<"大于20岁的人员个数为:"<<num<<endl;
}
int main(){
//test01();
test02();
system("pause");
return 0;
}
学习目标:
- 掌握常用的排序算法
算法简介:
- sort //对容器内元素进行排序
- random_shuffle //洗牌 指定范围内的元素随机调整次序
- merge //容器元素合并,并存储到另一容器中
- reverse //反转指定范围的元素
功能描述:
- 对容器内元素进行排序
函数原型:
-
sort(iterator beg,iterator end,_Pred)
//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
//beg 开始迭代器
//end 结束迭代器
//_Pred 谓词
示例:
#include<iostream>
using namespace std;
#include <algorithm>
#include<vector>
#include<functional>
//常用的排序算法 sort
void myPrint(int val)
{
cout<<val<<" ";
}
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(30);
v.push_back(50);
v.push_back(40);
v.push_back(20);
//利用sort
sort(v.begin(),v.end());
for_each(v.begin(),v.end(),myPrint);
cout<<endl;
//改变为降序
sort(v.begin(),v.end(),greater<int>());
}
int main()
{
test01();
system("pause");
return 0;
}
功能描述:
- 洗牌 指定范围内的元素随机调整次序
函数原型:
-
random_shuffle(iterator beg,iterator end);
//指定范围内的元素随机调整次序
//beg 开始迭代器
//end 结束迭代器
示例:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<ctime>
#include<functional>
//常用的排序算法 random_shuffle
void myPrint(int val)
{
cout<<val<<" ";
}
void test01()
{
srand((unsigned int)time(NULL))
vector<int> v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
//利用洗牌 算法 打乱顺序
random_shuffle(v.begin(),v.end());
for_each(v.begin(),v.end(),myPrint);
cout<<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
功能描述:
- 两个容器元素合并,并存储到另一容器中
函数原型:
-
merge(iterator beg1,iterator end1,iterator beg2,iterator end2,iterator dest);
//容器元素合并,并存储到另一容器中
//注意:两个容器必须是有序的
//beg1 容器 1 开始迭代器
//end1 容器 1 结束迭代器
//beg2 容器 2 开始迭代器
//end2 容器 2 结束迭代器
//dest 目标容器开始迭代器
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
#include <string>
//常用的排序算法 merge
void myPrint(int val)
{
cout<<val<<" ";
}
void test01()
{
vector<int> v1;
vector<int> v2;
for (int i = 0; i <10 ; i++) {
v1.push_back(i);
v2.push_back(i+1);
}
//目标容器
vector<int> vTarget;
//提前给目标容器分配空间
vTarget.resize(v1.size()+v2.size());
merge(v1.begin(),v1.end(),v2.begin(),v2.end(),vTarget.begin());
for_each(vTarget.begin(),vTarget.end(),myPrint);
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
功能描述:
- 将容器内元素进行反转
函数原型:
-
reverse(iterator beg,iterator end)
//反转指定范围的元素
//beg 开始迭代器
//end 结束迭代器
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
#include <string>
//常用的排序算法 reverse
void myPrint(int val)
{
cout<<val<<" ";
}
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
cout<<"反转前:"<<endl;
for_each(v.begin(),v.end(),myPrint);
cout<<endl;
cout<<"反转后:"<<endl;
reverse(v.begin(),v.end());
for_each(v.begin(),v.end(),myPrint);
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
学习目标:
- 掌握常用的拷贝和替换算法
算法简介:
- copy //容器内指定范围的元素拷贝到另一容器中
- replace //将容器内指定范围的旧元素修改为新元素
- replace_if //容器内指定范围满足条件的元素替换为新元素
- swap //互换两个容器的元素
功能描述:
- 容器内指定乏味的元素拷贝到另一容器中
函数原型:
- copy(iterator beg,iterator end, iterator dest);
//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
//beg 开始迭代器
//end 结束迭代器
//dest 目标起始迭代器
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
//常用的拷贝和替换算法 copy
void myPrint(int val)
{
cout<<val<<" ";
}
void test01()
{
vector<int> v;
for(int i=0;i<10;i++){
v.push_back(i);
}
vector<int> v2;
v2.resize(v.size());
copy(v.begin(),v.end(),v2.begin());
for_each(v2.begin(),v2.end(),myPrint);
}
int main(){
test01();
system("pause");
return 0;
}
功能描述:
- 将容器内指定范围的旧元素修改为新元素
函数原型:
-
replace(iterator beg,iterator end,oldvalue,newvalue);
//将区间内旧元素替换成新元素
//beg 开始迭代器
//end 结束迭代器
//oldvalue 旧元素
//newvalue 新元素
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
//常用的拷贝和替换算法 replace
void myPrint(int val)
{
cout<<val<<" ";
}
void test01()
{
vector<int> v;
for(int i=0;i<10;i++){
v.push_back(i);
}
replace(v.begin(),v.end(),0,100);
for_each(v.begin(),v.end(),myPrint);
}
int main(){
test01();
system("pause");
return 0;
}
功能描述:
- 将区间内满足条件的元素,替换成指定元素
函数原型:
-
replace_if(iterator beg,iterator end,_pred,newvalue);
//按条件替换元素,满足条件的替换成指定元素
//beg 开始迭代器
//end 结束迭代器
//_pred 谓词
//newvalue 替换的新元素
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
//常用的拷贝和替换算法 replace_if
class Greater5
{
public:
bool operator()(int val)
{
return val>=5;
}
};
void myPrint(int val)
{
cout<<val<<" ";
}
void test01()
{
vector<int> v;
for(int i=0;i<10;i++){
v.push_back(i);
}
cout<<"替换前:"<<endl;
for_each(v.begin(),v.end(),myPrint);
cout<<endl;
cout<<"替换后:"<<endl;
replace_if(v.begin(),v.end(),Greater5(),20);
for_each(v.begin(),v.end(),myPrint);
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
功能描述:
- 互换两个容器的元素
函数原型:
-
swap(container c1,container c2);
//互换两个容器的元素
//c1 容器 1
//c2 容器 2
示例:
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法的头文件
//常用的拷贝和替换算法 swap
void myPrint(int val)
{
cout<<val<<" ";
}
void test01()
{
vector<int> v1;
vector<int> v2;
for (int i = 0; i <10 ; i++) {
v1.push_back(i);
v2.push_back(i+100);
}
cout<<"交换前:"<<endl;
for_each(v1.begin(),v1.end(),myPrint);
cout<<endl;
for_each(v2.begin(),v2.end(),myPrint);
cout<<endl;
cout<<"交换后:"<<endl;
swap(v1,v2);
for_each(v1.begin(),v1.end(),myPrint);
cout<<endl;
for_each(v2.begin(),v2.end(),myPrint);
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
学习目标:
- 掌握常用的算术生成算法
注意:
- 算术生成算法属于小型算法,使用是包含的头文件为#include< numeric >
算法简介:
- accumulate //计算容器元素累计总和
- fill //向容器中添加元素
功能描述:
- 计算区间内容器元素累计总和
函数原型:
-
accumulate(iterator beg,iterator end,value)
//计算容器元素累计总和
//beg 开始迭代器
//end 结束迭代器
//value 起始值
示例:
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
//常用算术生成算法
void test01(){
vector<int>v;
for(int i=0;i<=100;i++)
{
v.push_back(i);
}
int total=accumulate(v.begin(),v.end(),0);
cout<<"total="<<total<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:accumulate 使用是头文件注意是 numeric,这个算法很实用
功能描述:
- 向容器中填充指定的元素
函数原型:
-
fill(iterator beg,iterator end,value);
//向容器中填充元素
//beg 开始迭代器
//end 结束迭代器
//value 填充的值
示例:
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
#include <algorithm>
//常用算术生成算法
void myPrint(int val){
cout<<val<<" ";
}
void test01(){
vector<int>v;
v.resize(10);
//后期重新填充
fill(v.begin(),v.end(),100);
for_each(v.begin(),v.end(),myPrint);
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:利用 fill 可以将容器区间内元素填充为指定的值
学习目标:
- 掌握常用的集合算法
算法简介:
- set_intersection //求两个容器的交集
- set_union //求两个容器的并集
- set_difference //求两个容器的差集
功能描述:
- 求两个容器的交集
函数原型:
-
set_intersection(iterator beg1,iterator end1,iterator beg2,iterator end2,iterator dest);
//求两个集合的交集
//beg1,第一个容器的开始迭代器
//end1,第一个容器的结束迭代器
//beg2,第二个容器的开始迭代器
//end2,第二个元素的结束迭代器
//dest, 目标容器的开始迭代器
示例:
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
#include <algorithm>
//常用算术生成算法
void myPrint(int val){
cout<<val<<" ";
}
void test01(){
vector<int>v1;
vector<int>v2;
for(int i=0;i<10;i++){
v1.push_back(i);
v2.push_back(i+5);
}
vector<int>vTarget;
//目标容器需要提前开辟空间
//最特殊情况,大容器包含小容器,开辟空间取小容器的size即可
vTarget.resize(min(v1.size(),v2.size()));
vector<int>::iterator itEnd=set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),vTarget.begin());
for_each(vTarget.begin(),itEnd,myPrint);
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- 求交集的两个集合必须的有序序列
- 目标容器开辟空间需要从两个容器中取最小值
- set_intersection 返回值即是交集中最后一个元素的问题
功能描述:
- 求两个集合的并集
函数原型:
-
set_union(iterator beg1,iterator end1,iterator beg2,iterator end2,iterator dest)
//求两个容器集合的并集
//注意:两个集合必须是有序序列
//beg1,第一个容器的开始迭代器
//end1,第一个容器的结束迭代器
//beg2,第二个容器的开始迭代器
//end2,第二个元素的结束迭代器
//dest, 目标容器的开始迭代器
示例:
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
#include <algorithm>
//常用算术生成算法
void myPrint(int val){
cout<<val<<" ";
}
void test01(){
vector<int>v1;
vector<int>v2;
for(int i=0;i<10;i++){
v1.push_back(i);
v2.push_back(i+5);
}
vector<int>vTarget;
//目标容器需要提前开辟空间
//最特殊情况,两个容器没有交集,并集是两个容器size相加
vTarget.resize(v1.size()+v2.size());
vector<int>::iterator itEnd=set_union(v1.begin(),v1.end(),v2.begin(),v2.end(),vTarget.begin());
for_each(vTarget.begin(),itEnd,myPrint);
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- 求并集的两个集合必须是有序序列
- 目标容器开辟空间需要两个容器相加
- set_union 返回值即是并集中最后一个元素的位置
功能描述:
- 求两个集合的差集
函数原型:
-
set_difference(iterator beg1,iterator end1,iterator beg2,iterator end2,iterator dest)
//求两个容器集合的并集
//注意:两个集合必须是有序序列
//beg1,第一个容器的开始迭代器
//end1,第一个容器的结束迭代器
//beg2,第二个容器的开始迭代器
//end2,第二个元素的结束迭代器
//dest, 目标容器的开始迭代器
示例:
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
#include <algorithm>
//常用算术生成算法
void myPrint(int val){
cout<<val<<" ";
}
void test01(){
vector<int>v1;
vector<int>v2;
for(int i=0;i<10;i++){
v1.push_back(i);
v2.push_back(i+5);
}
vector<int>vTarget;
//目标容器需要提前开辟空间
//最特殊情况,两个容器没有交集,并集是两个容器size相加
vTarget.resize(max(v1.size(),v2.size()));
vector<int>::iterator itEnd=set_difference(v1.begin(),v1.end(),v2.begin(),v2.end(),vTarget.begin());
for_each(vTarget.begin(),itEnd,myPrint);
cout<<endl;
}
int main(){
test01();
system("pause");
return 0;
}
总结:
- 求差集的两个集合必须是有序序列
- 目标容器开辟空间需要从两个容器取较大值
- set_difference 返回值即是差集中最后一个元素的位置