C++编程基础

C++编程基础

1.类和IO库

4.类和对象

4.1封装

属性和行为作为整体
#include<iostream>
using namespace std;
#include<string>
const double PI = 3.14;

class Circle {

public:
	int m_r;

	double calculateZC() {
		return 2 * PI * m_r;
	}
};

int main()
{
	Circle cl;
	cl.m_r = 10;
	cout << "圆的周长=" << cl.calculateZC() << endl;
	system("pause");
	return 0;

}
案例-设计学生类
#include<iostream>
using namespace std;
#include<string>

class Student {
public:
	//类中的属性和行为	我们统一称为	成员
	//属性		成员属性	成员变量
	//行为		成员函数	成员方法
	
	//属性
	string m_Name;
	int m_Id;
	//行为
	//给姓名赋值
	void setName(string name) {
		m_Name = name;
	}
	void showStudent() {
		cout << "姓名:" << m_Name << " 学号:" << m_Id << endl;
	}
};

int main()
{
	Student  s1;
	Student  s2;
	s1.m_Name = "张三";
	s1.m_Id = 1;
	s1.showStudent();
	
	s2.setName("李四");
	s2.m_Id = 2;
	s2.showStudent();

	system("pause");
	return 0;
}
访问权限

​ 类在设计时,可以把属性和行为放在不同的权限下,加以控制

访问权限有三种:

  1. public 公共权限 类内可以访问 类外可以访问
  2. protected 保护权限 类内可以访问 类外不可以访问
  3. private 私有权限 类内可以访问 类外不可以访问
#include<iostream>
using namespace std;
#include<string>

class Person {
public:
	string m_name;

protected:
	string m_car;

private:
	int m_password;

public:
	void func()
	{
		m_name = "张三";
		m_car = "拖拉机";
		m_password = 123456;
	}

};

int main()
{
	Person p1;
	p1.m_name = "李四";
	//p1.m_car = "奔驰";//保护权限内容,在类外访问不到
	//p1.m_Password = 123;//私有权限内容,类外访问不到

	system("pause");
	return 0;
}
struct和class区别

在C++中struct和class唯一的区别就在于默认的访问权限不同

区别:

  • struct 默认权限为公共

  • class默认权限为私有

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

class C1 {
	int m_A; //默认是私有权限
};
struct c2 {
	int m_A; //默认是公共权限
};
int main() {
	C1 c1;
	//c1.m_A = 10;//错误,访问权限是私有
	c2 c2;
	c2.m_A = 10; // 正确,访问权限是公共

	system("pause");
	return 0;
}
成员属性设置为私有

优点1:将所有成员属性设置为私有,可以自己控制读写权限

优点2:对于写权限,我们可以检测数据的有效性

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

class Person {
public:
	//姓名设置可读可写
	void setName(string name) {
		m_Name = name;
	}
	string getName() {
		return m_Name;
	}
	//获取年龄
	int getAge()
	{
		return m_Age;
	}
	//设置年龄
	void setAge(int age) {
		if (age < 0 || age > 150) {
			cout << "你个老妖精!" << endl;
			return;
		}
		m_Age = age;
	}
	//情人设置为只写
	void setLover(string lover) {
		m_Lover = lover;
	}
private:
	string m_Name; //可读可写姓名
	int m_Age; // 只读年龄
	string m_Lover;//只写情人
};
int main() {
	Person p;//姓名设置
	p.setName("张三");
	cout << "姓名:" << p.getName() << endl;
	//年龄设置
	p.setAge(50),
	cout << "年龄:" << p.getAge() << endl;
	//情人设置
	p.setLover("小王");
	//cout<<"情人:" << p.m_Lover << endl; // 只写属性,不可以读取
	system("pause");
	return 0;
}
练习案例1:设计立方体类

设计立方体类(Cube)

求出立方体的面积和体积

分别用全局函数和成员函故判断两个立方体是否相等。

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

//立方体类设计 
//1、创建立方体类 
//2、设计属性
//3、设计行为获取立方体面积和体积
//4、分别利用全局函数和成员函数判断两个立方体是否相等

class Cube {
public:
	//设置长
	void setL(int l) {
		m_L = l;
	}
	//获取长
	int getL() {
		return m_L;
	}

	void setW(int w) {
		m_W = w;
	}
	int getW() {
		return m_W;
	}

	void setH(int h) {
		m_H = h;
	}
	int getH() {
		return m_H;
	}
	int calculateS()
	{
		return 2 * m_L * m_W + 2 * m_W * m_H + 2 * m_L * m_H;
	}
	int calculateV()
	{
		return m_L * m_W * m_H;
	}
private:
	int m_L;
	int m_W;
	int m_H;
};
//利用全局函数判断两个立方体是否相等
bool isSame (Cube &c1 , Cube &c2){
	if (c1.getL() == c2.getL() && c1.getW() == c2.getW() && c1.getH() == c2.getH())
	{
		return true;
	}
		return false;
}
int main() {
	Cube c1;
	c1.setL(10);
	c1.setW(10);
	c1.setH(10);
	// 600
	cout << "c1的面积为:" << c1.calculateS() << endl;
	// 1000
	cout << "c1的体积为:" << c1.calculateV() << endl;

	Cube c2;
	c2.setL(10);
	c2.setW(10);
	c2.setH(10);

	bool ret = isSame(c1, c2);
	if (ret)
	{
		cout << "c1和c2是相等的" << endl;
	}
	else
	{
		cout << "c1和c2是不相等的" << endl;
	}
	system("pause");
	return 0;
}
案例2:点和圆的关系
#include<iostream>
using namespace std;
#include<string>
#include"point.h"
#include"circle.h"

//class Point {
//public:
//	void setX(int x) {
//		m_X = x;
//	}
//	int getX() {
//		return m_X;
//	}
//	void setY(int y) {
//		m_Y = y;
//	}
//	int getY() {
//		return m_Y;
//	}
//private:
//	int m_X;
//	int m_Y;
//};
//class Circle{
//public:
//	void setR(int r) {
//		m_R = r;
//	}
//	int getR() {
//		return m_R;
//	}
//	void setCenter(Point center) {
//		m_Center = center;
//	}
//	Point getCenter() {
//		return m_Center;
//	}
//private:
//	int m_R;
//	Point m_Center;
//};
//判断点和圆关系
void isInCircle(Circle &c, Point &p) {
	//计算两点之间距离平方
	int distance =
		(c.getCenter().getX() - p.getX()) * (c.getCenter().getX() - p.getX()) +
		(c.getCenter().getY() - p.getY()) * (c.getCenter().getY() - p.getY());
		//计算半径的平方
	int rDistance = c.getR()* c.getR();
	//判断关系
	if (distance == rDistance)
	{
		cout << "点在圆上" << endl;
	}
	else if (distance > rDistance) {
		cout << "点在圆外" << endl;
	}
	else
	{
		cout << "点在圆内" << endl;
	}
}
int main() {
	Circle c;
	c.setR(10);
	Point center;
	center.setX(10);
	center.setY(0);
	c.setCenter(center);
	//创建点
	Point p;
	p.setX(10);
	p.setY(9);
	isInCircle(c,p);

	system("pause");
	return 0;
}

point.h

#pragma once
#include<iostream>
using namespace std;
class Point {
public:
	void setX(int x);
	int getX();
	void setY(int y);
	int getY() ;
private:
	int m_X;
	int m_Y;
};

circle.h

#pragma once
#include<iostream>
using namespace std;
#include"point.h"

class Circle {
public:
	void setR(int r);
	int getR();
	void setCenter(Point center);
	Point getCenter();
private:
	int m_R;
	Point m_Center;
};

point.cpp

#include"point.h"

void Point::setX(int x) {
	m_X = x;
}
int Point::getX() {
	return m_X;
}
void Point::setY(int y) {
	m_Y = y;
}
int Point::getY() {
	return m_Y;
}

circle.cpp

#include"circle.h"

void Circle::setR(int r) {
	m_R = r;
}
int Circle::getR() {
	return m_R;
}
void Circle::setCenter(Point center) {
	m_Center = center;
}
Point Circle::getCenter() {
	return m_Center;
}

main.cpp

#include<iostream>
using namespace std;
#include<string>
#include"point.h"
#include"circle.h"

//判断点和圆关系
void isInCircle(Circle &c, Point &p) {
	//计算两点之间距离平方
	int distance =
		(c.getCenter().getX() - p.getX()) * (c.getCenter().getX() - p.getX()) +
		(c.getCenter().getY() - p.getY()) * (c.getCenter().getY() - p.getY());
		//计算半径的平方
	int rDistance = c.getR()* c.getR();
	//判断关系
	if (distance == rDistance)
	{
		cout << "点在圆上" << endl;
	}
	else if (distance > rDistance) {
		cout << "点在圆外" << endl;
	}
	else
	{
		cout << "点在圆内" << endl;
	}
}
int main() {
	Circle c;
	c.setR(10);
	Point center;
	center.setX(10);
	center.setY(0);
	c.setCenter(center);
	//创建点
	Point p;
	p.setX(10);
	p.setY(9);
	isInCircle(c,p);

	system("pause");
	return 0;
}

4.2对象的初始化和清理

C++中的面向对象来源于生活,每个对象也都会有初始设置以及对象销毁前的清理数据的设置。

4.2.1构造函数和析构函数
  • 对象的初始化和清理也是两个非常重要的安全问题

    ​ 一个对象或者变量没有初始状态,对其使用后果是未知

    ​ 同样的使用完一个对象或变量,没有及时清理,也会造成一定的安全问题

C++利用了构造函数和析构函数解决上述问题,这两个函教将会被编译器自动调用,完成对象初始化和清理工作。对象的初始化和清理工作是编译器强制要我们做的事情,因此如果我们不提供构造和析构,编译器会提供
编译器提供的构造函数和析构函数是空实现.

  • 构造函数:主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用。

  • 析构函数:主要作用在于对象销毁前系统自动调用,执行一些清理工作。

构造函数语法: 类名(){}
1.构造函数,没有返回值也不写void

2.函数名称与类名相同

3.构造函数可以有参数,因此可以发生重载

4.程序在调用对象时候会自动调用构造,无须手动调用,而且只会调用一次

析构函数语法: ~类名(){}
1.析构函数,没有返回值也不写void

2.函数名称与类名相同,在名称前加上符号~

3.析构函数不可以有参数,因此不可以发生重载Ⅰ

4.程序在对象销毁前会自动调用析构,无须手动调用,而且只会调用一次

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

class Person {
public:
	//构造函数
	Person()
	{
		cout << "Person 构造函数的调用" << endl;
	}
	//析构函数
	~Person()
	{
		cout << "Person 析构函数的调用" << endl;
	}
};
void test01() {
	Person p;
}
int main() {
	test01();
	system("pause");
	return 0;
}
4.2.2构造函数的分类及调用

两种分类方式:

  • 按参数分为:有参构造和无参构造

  • 按类型分为:普通构造和拷贝构造

三种调用方式:

  1. 括号法
  2. 显示法
  3. 隐式转换法
#include<iostream>
using namespace std;
#include<string>

class Person {
public:
	//构造函数
	Person()
	{
		cout << "Person 无参构造函数的调用" << endl;
	}
	Person(int a)
	{
		age = a;
		cout << "Person 有参构造函数的调用" << endl;
	}
	//拷贝构造函数
	Person(const Person &p)
	{
		age = p.age;
		cout << "Person 拷贝构造函数的调用" << endl;
	}
	//析构函数
	~Person()
	{
		cout << "Person 析构函数的调用" << endl;
	}
	int age;
};
//调用
void test01() {
	//1、括号法
	Person p1;//默认构造函数调用
	Person p2(10);//有参构造函数
	Person p3(p2);

	//注意事项
	//调用默认构造函数时候,不要加()
	//因为下面这行代码,编译器会认为是一个函数的声明
	Person p1();

	//2/显示法
	Person p1;
	Person p2 = Person(10);
	Person p3 = Person(p2);

	Person(10);//匿名对象,特点:当前行执行结束后,系统会立即回收掉匿名对象
	//注意事项2
	//不要利用拷贝构造函数初始化匿名对象 Person(p3) == = Person p3;对象声明
	//Person(p3);
	//3、隐式转换法
	Person p4 = 10;//相当于Person p4 = Person(10);
	Person p5 = p4;
}
int main() {
	test01();

	system("pause");
	return 0;
}
4.2.3拷贝构造函数调用时机

C++中拷贝构造函数调用时机通常有三种情况

  • 使用一个已经创建完毕的对象来初始化一个新对象

  • 值传递的方式给函数参数传值

  • 以值方式返回局部对象

#include<iostream>
using namespace std;

class Person {
public:
	//构造函数
	Person()
	{
		cout << "Person 默认构造函数的调用" << endl;
	}
	Person(int a)
	{
		m_age = a;
		cout << "Person 有参构造函数的调用" << endl;
	}
	//拷贝构造函数
	Person(const Person &p)
	{
		m_age = p.m_age;
		cout << "Person 拷贝构造函数的调用" << endl;
	}
	~Person()
	{
		cout << "Person 析构函数的调用" << endl;
	}
	int m_age;
};
//调用
void test01() {
	Person p1(20);
	Person p2(p1);
}
void doWork2(Person p)
{

}
void test02() {
	Person p3;
	doWork2(p3);
}
Person doWork3()
{
	Person p1;
	cout << (int*)&p1 << endl;
	return p1;
}
void test03() {
	Person p = doWork3();
	cout << (int*)&p << endl;
}
int main() {
	//test01();
	test03();
	system("pause");
	return 0;
}
4.2.4构造函数调用规则

默认情况下,C++编译器至少给一个类添加3个函数

  1. 默认构造函教(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝

构造函数调用规则如下:

  • 如果用户定义有参构造函数,c++不在提供默认无参构造,但是会提供默认拷贝构造

  • 如果用户定义拷贝构造函数,c++不会再提供其他构造函数

4.2.5深拷贝与浅拷贝

深浅拷贝是面试经典问题,也是常见的一个坑

浅拷贝:简单的赋值拷贝操作

深拷贝:在堆区重新申请空间,进行拷贝操作

  • Person p2(p1)如果利用编译器提供的拷贝构造函数,会做浅拷贝操作

  • 浅拷贝带来的问题就是堆区的内存重复释放 要利用深拷贝进行解决

总结:如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题

#include<iostream>
using namespace std;

class Person {
public:
	//构造函数
	Person()
	{
		cout << "Person 默认构造函数的调用" << endl;
	}
	Person(int age,int height)
	{
		m_age = age;
		m_height = new int(height);
		cout << "Person 有参构造函数的调用" << endl;
	}
	//拷贝构造函数
	Person(const Person &p)
	{
		
		cout << "Person 拷贝构造函数的调用" << endl;
		m_age = p.m_age;
		//m_height = p.m_height; 编译器默认实现的
		//深拷贝操作
		m_height=new int(*p.m_height);
	}
	~Person()
	{
		if (m_height != NULL)
		{
			delete m_height;
		}
		cout << "Person 析构函数的调用" << endl;
	}
	int m_age;
	int *m_height;
};
//调用
void test01() {
	Person p1(18,160);
	cout << "p1的年龄为" << p1.m_age << " p1的身高为" << *p1.m_height << endl;
	
	Person p2(p1);
	cout << "p2的年龄为" << p2.m_age << " p2的身高为" << *p2.m_height << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
4.2.6初始化列表

作用:C++提供了初始化列表语法,用来初始化属性

语法:构造函数():属性1(值1),展性2(值2)…()

#include<iostream>
using namespace std;

class Person {
public:
	//构造函数
	/*Person()
	{
		cout << "Person 默认构造函数的调用" << endl;
	}*/
	// 传统初始化操作
	/*Person(int a,int b,int c)
	{
		m_a = a;
		m_b = b;
		m_c = c;
		cout << "Person 有参构造函数的调用" << endl;
	}*/
	//初始化列表初始化属性
	Person():m_a(10), m_b(20), m_c(30)
	{

	}
	Person(int a,int b,int c):m_a(a), m_b(b), m_c(c)
	{

	}
	~Person()
	{
		cout << "Person 析构函数的调用" << endl;
	}
	int m_a;
	int m_b;
	int m_c;
};
//调用
void test01() {
	//Person p(10,20,30);
	Person p;
	cout << "m_a=" << p.m_a << "  m_b=" << p.m_b << "  m_c=" << p.m_c << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
4.2.7类对象作为类成员

C++类中的成员可以是另一个类的对象,我们称该成员为对象成员

class A{}
class B
{
    A a;
}

B类中有对象A作为成员,A为对象成员

那么当创建B对象时,A与B的构造和析构的顺序是谁先谁后?

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

class Phone {
public:
	Phone(string pname) {
		m_pname = pname;
		cout << "Phone的构造函数调用" << endl;
	}
	~Phone() {
		cout << "Phone的析构函数调用" << endl;
	}
	//手机品牌名
	string m_pname;
};
class Person {
public:

	Person(string name, string pname) :m_name(name), m_phone(pname) {
		cout << "Person的构造函数调用" << endl;
	}
	~Person() {
		cout << "Person的析构函数调用" << endl;
	}
	//姓名
	string m_name;
	//手机
	Phone m_phone;
};
//调用
void test01() {
	Person p("张三", "华为");
	cout << p.m_name << "拿着" << p.m_phone.m_pname << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}#include<iostream>
using namespace std;
#include<string>

class Phone {
public:
	Phone(string pname) {
		m_pname = pname;
		cout << "Phone的构造函数调用" << endl;
	}
	~Phone() {
		cout << "Phone的析构函数调用" << endl;
	}
	//手机品牌名
	string m_pname;
};
class Person {
public:

	Person(string name, string pname) :m_name(name), m_phone(pname) {
		cout << "Person的构造函数调用" << endl;
	}
	~Person() {
		cout << "Person的析构函数调用" << endl;
	}
	//姓名
	string m_name;
	//手机
	Phone m_phone;
};
//调用
void test01() {
	Person p("张三", "华为");
	cout << p.m_name << "拿着" << p.m_phone.m_pname << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
4.2.8静态成员

静态成员就是在成员变量和成员函数前加上关键字static,称为静态成员

静态成员分为:

  • 静态成员变量
  1. 所有对象共享同一份数据。
  2. 在编译阶段分配内存
  3. 内声明,类外初始化
  • 静态成员函数
  1. 所有对象共享同一个函数
  2. 静态成员函数只能访问静态成员变量
#include<iostream>
using namespace std;
#include<string>

class Person {
public:
	//静态成员函数
	static void func() {
		m_a = 100;//静态成员函数可以访问静态成员变量
		//m_b = 200;// 静态成员函数不可以访问非静态成员变量,无法区分是哪个对象的m_b属性
		cout << "static void func 的调用" << endl;
	}
	static int m_a;//静态成员变量
	int m_b;//非静态成员变量

	//静态成员函数也是有访问权限的
private:
	static void func2() {
		cout << "static void func2 的调用" << endl;
	}
};
int Person::m_a = 0;
//两种访问方式
void test01() {
	//1.通过对象访问
	Person p;
	p.func();
	//2.通过类名访问
	Person::func();  //共享同一个
	//Person::func2();//类外访问不到私有静态成员函数
}
int main() {
	test01();
	system("pause");
	return 0;
}

4.3 C++对象模型和this指针

4.3.1成员变量和成员函数分开存储

在C++中,类内的成员变呈和成员函数分开存储

只有非静态成员变量才属于类的对象上

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

class Person {
	int m_a;//非静态成员变量 属于类的对象上
	static int m_b;//静态成员 不属于类对象上
	void func() {}//非静态成员函数 不属于类对象上
	static void func2() {};//静态成员函数 不属于类对象上
};

void test01() {
	Person p;
	//空对象占用内存空间为:1
	//C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置
	// 每个空对象也应该有一个独一无二的内存地址
	cout << "size of p = " << sizeof(p) << endl;
}
void test02() {
	Person p;
	cout << "size of p = " << sizeof(p) << endl;
}
int main() {
	test02();
	system("pause");
	return 0;
}
4.3.2 this指针概念

通过4.3.1我们知道在C++中成员变量和成员函数是分开存储的

每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用一块代码

那么问题是:这一块代码是如何区分那个对象调用自己的呢?

C++通过提供特殊的对象指针,this指针,解决上述问题。this指针指向被调用的成员函数所属的对象

this指针是隐含每一个非静态成员函数内的一种指针

this指针不需要定义,直接使用即可

this指针的用途:

  • 当形参和成员变量同名时,可用this指针来区分
  • 在类的非静态成员函数中返回对象本身,可使用return *this
#include<iostream>
using namespace std;

class Person {
public:
	Person(int age) {
		//this指针指向被调用的成员函数所属的对象
		this->age = age;
	}
	Person& PersonADDage(Person &p) {
		this->age += p.age;
		//this指向p2的指针,而*this指向的就是p2这个对象本体
		return *this;
	}
	int age;
};
//1.解决名称冲突
void test01() {
	Person p1(18);
	cout << "p1的年龄为: " << p1.age << endl;
}
//2.返回对象本身用*this
void test02() {
	Person p1(10);
	Person p2(10);
	p2.PersonADDage(p1).PersonADDage(p1);
	cout << "p2的年龄为: " << p2.age << endl;
}

int main() {
	test02();
	system("pause");
	return 0;
}
4.3.3空指针访问成员函数

C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针

如果用到this指针,需要加以判断保证代码的健壮性

#include<iostream>
using namespace std;

class Person {
public:
	void showClassName() {
		cout << "this is Person class" << endl;
	}
	void showClassAge() {
		//报错原因是因为传入的指针是为NULL
		if (this == NULL)
		{
			return;
		}
		cout << "age= " << this->m_age << endl;
	}
	int m_age;
};
//1.解决名称冲突
void test01() {
	Person *p = NULL;
	p->showClassName();
	p->showClassAge();
}

int main() {
	test01();
	system("pause");
	return 0;
}
4.3.4 const修饰成员函数

常函数:

  • 成员函数后加const后我们称为这个函数为常函数
  • 常函教内不可以修改成员属性
  • 成员属性声明时加关键字mutable后,在常函数中依然可以修改

常对象:

  • 声明对象前加const称该对象为常对象
  • 常对象只能调用常函数
#include<iostream>
using namespace std;

//常函数
class Person {
public:
	//this指针的本质是指针常量 指针的指向是不可以修改的
	//const Person * const this;
	//在成员函数后面加const,修饰的是this指向,让指针指向的值也不可以修改
	void showPerson() const //相当于上一行
	{
		this->m_b = 100;
		//this->m_a = 100;
		// this = NULL; //this指针不可以修改指针的指向的

	}
	void func(){}
	int m_a;
	mutable int m_b;//特殊变量,即使在常函数中,也可以修改这个值,加关键字mutable
};
//1.解决名称冲突
void test01() 
{
	Person p;
	p.showPerson();
}
//常对象
void test02() 
{
	const Person p;//在对象前加const,变为常对象
	//p.m_a = 100;
	p.m_b = 100;//m_B是特殊值,在常对象下也可以修改
	
	//常对象只能调用常函数
	p. showPerson() ;
	//p.func();//常对象不可以调用普通成员函数,因为普通成员函数可以修改属性

}

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

4.4友元

生活中你的家有客厅(Public),有你的卧室(Private)

客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去

但是呢,你也可以允许你的好闺蜜好基友进去。

在程序里,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术

友元的目的就是让一个函教或者类访问另一个类中私有成员

友元的关键字为friend

友元的三种实现

  • 全局函教做友元
  • 类做友元
  • 成员函数做友元
1.全局函教做友元
#include<iostream>
using namespace std;
#include<string>

class Building
{
	// goodGay全局函数是 Building好朋友,可以访问Building中私有成员
	friend void goodGay(Building *building);
public:
	Building()
	{
		m_SittingRoom = "客厅";
		m_BedRoom = "卧室";
	}
public:
	string m_SittingRoom;//客厅

private:
	string m_BedRoom;//卧室
};
//全局函数
void goodGay(Building *building) 
{
	cout << "好基友的全局函数 正在访问:" << building->m_SittingRoom << endl;
	cout << "好基友的全局函数 正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
	Building building;
	goodGay(&building);
}
int main() {
	test01();
	system("pause");
	return 0;
}
2.类做友元
#include<iostream>
using namespace std;
#include<string>

class Building;
class GoodGay
{
public:
	void visit();//参观函数访问Building中的属性
	Building * building;
	GoodGay();
private:
	Building *building;
};
class Building
{
	friend class GoodGay;
public:
	Building();
public:
	string m_SittingRoom;//客厅
private:
	string m_BedRoom;//卧室
};

Building::Building()
{
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
	//创建建筑物对象
	building = new Building;
}
void GoodGay::visit()
{
	cout << "好基友的全局函数 正在访问:" << building->m_SittingRoom << endl;
	cout << "好基友的全局函数 正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
	GoodGay gg;
	gg.visit();
}
int main() {
	test01();
	system("pause");
	return 0;
}
3.成员函数做友元
#include<iostream>
using namespace std;
#include<string>

class Building;
class GoodGay
{
public:
	GoodGay();
	
	void visit();//让visit函数可以访问Building中私有成员
	void visit2();//让visit函数不可以访问Building中私有成员
	
private:
	Building *building;
};
class Building
{
	friend void GoodGay::visit();
public:
	Building();
public:
	string m_SittingRoom;//客厅
private:
	string m_BedRoom;//卧室
};

Building::Building()
{
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
	//创建建筑物对象
	building = new Building;
}
void GoodGay::visit()
{
	cout << "好基友的全局函数 正在访问:" << building->m_SittingRoom << endl;
	cout << "好基友的全局函数 正在访问:" << building->m_BedRoom << endl;
}
void GoodGay::visit2()
{
	cout << "好基友的全局函数 正在访问:" << building->m_SittingRoom << endl;
	//cout << "好基友的全局函数 正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
	GoodGay gg;
	gg.visit();
	gg.visit2();
}
int main() {
	test01();
	system("pause");
	return 0;
}

4.5运算符重载

运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

4.5.1加号运算符重载

作用:实现两个自定义数据类型相加的运算

image-20220406213443718image-20220406213502489image-20220406213443718image-20220406213502489

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

class Person
{
public:
	//1.成员函数重载+号
	//Person operator+(Person &p)
	//{
	//	Person temp;
	//	temp.m_a = this->m_a + p.m_a;
	//	temp.m_b = this->m_b + p.m_b;
	//	return temp;
	//}
	int m_a;
	int m_b;
};
//2.全局函数重载+号
Person operator+(Person &p1, Person &p2)
{
	Person temp;
	temp.m_a = p1.m_a + p2.m_a;
	temp.m_b = p1.m_b + p2.m_b;
	return temp;
}
//函数重载版本
Person operator+(Person &p1, int num)
{
	Person temp;
	temp.m_a = p1.m_a + num;
	temp.m_b = p1.m_b + num;
	return temp;
}
void test01()
{
	Person p1;
	p1.m_a = 10;
	p1.m_b = 10;
	Person p2;
	p2.m_a = 10;
	p2.m_b = 10;
	//成员函数重载本质调用
	//Person p3 = p1.operator+(p2);
	//全局函数重载本质调用
	//Person p3 = operator+(p1,p2);
	Person p3 = p1 + p2;
	
	//函数重载
	Person p4 = p1 + 100;

	cout << "p3.m_a = " << p3.m_a << endl;
	cout << "p3.m_b = " << p3.m_b << endl;
	cout << "p4.m_a = " << p4.m_a << endl;
	cout << "p4.m_b = " << p4.m_b << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结1:对于内置的数据类型的表达式的的运算符是个可能改变的

总结2:不要溢用运算符重载

4.5.2左移运算符重载

作用:可以输出自定义教据类型

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

class Person
{
	//利用成员函数重载左移运算符p.operator<<(cout)简化版本p << cout
	//不会利用成员函数重载<<运算符,因为无法实现cout在左侧
	//void operator<<( cout )
	//{
	//}
	friend ostream& operator<<(ostream &cout, Person &p);
public:
	Person(int a,int b)
	{
		m_a = a;
		m_b = b;
	}
private:
	int m_a;
	int m_b;
};
//2.只能利用全局函数重载左移运算符
ostream& operator<<(ostream &cout, Person &p)//本质 operator<<(cout,p) 简化cout<<p
{
	cout << "m_a = " << p.m_a << " p.m_b = " << p.m_b;
	return cout;
}

void test01()
{
	Person p(10,10);
	
	cout << p <<" hello world!"<<endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
4.5.3递增运算符重载

作用:通过重载递增运算符,实现自己的整型教据

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

class MyInteger
{
	friend ostream& operator<<(ostream &cout, MyInteger &myint);
public:
	MyInteger()
	{
		m_num = 0;
	}
	//重载前置++运算符   返回引用为了一直对一个数据进行递增操作
	MyInteger& operator++()
	{
		m_num++;
		return *this;
	}
	//重载后置++运算符
	//void operator++(int) int代表占位参数,可以用于区分前置和后置递增
	//temp是局部对象  返回值,不返回引用
	MyInteger operator++(int)
	{
		//先记录当时结果
		MyInteger temp = *this;
		//后递增
		m_num++;
		// 最后将记录结果做返回
		return temp;

	}
private:
	int m_num;
};
//重载左移运算符
ostream& operator<<(ostream &cout, MyInteger &myint)
{
	cout << myint.m_num;
	return cout;
}

void test01()
{
	MyInteger myint;
	cout << ++myint << endl;
}
void test02()
{
	MyInteger myint;
	cout << myint++ << endl;
	cout << myint << endl;
}
int main() {
	test02();
	system("pause");
	return 0;
}

总结:前置递增返回引用,后置递增返回值

4.5.4赋值运算符重载

C++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函教体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝
  4. 赋值运算符operator=,对属性进行值拷贝

如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

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

class Person
{
public:
	Person(int age)
	{
		m_age =	new int(age);
	}
	~Person()
	{
		if (m_age != NULL)
		{
			delete m_age;
			m_age = NULL;
		}
	}
	//重载 赋值运算符
	Person& operator=(Person &p)
	{

		//编译器提供的是浅拷贝
		//m_age=p.m_age;
		//应该先判断是否有属性在堆区,如果有先释放干净,然后再深拷贝
		if (m_age != NULL)
		{
			delete m_age;
			m_age = NULL;
		}
		//深拷贝
		m_age = new int(*p.m_age);
		return *this;
	}
	int *m_age;
private:
};

void test01()
{
	Person p1(18);
	Person p2(20);
	Person p3(30);
	
	p3 = p2 = p1;//赋值操作

	cout << "p1的年龄为: " << *p1.m_age << endl;
	cout << "p2的年龄为: " << *p2.m_age << endl;
	cout << "p3的年龄为: " << *p3.m_age << endl;
}

int main() {
	test01();
	system("pause");
	return 0;
}
4.5.5关系运算符重载

作用:重载关系运算符,可以让两个自定义类型对象进行对比操作

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

class Person
{
public:
	Person(string name,int age)
	{
		m_name = name;
		m_age =	age;
	}
	//重载 ==号
	bool operator==(Person &p)
	{
		if (this->m_age == p.m_age && this->m_name == p.m_name)
		{
			return 1;
		}
		return 0;
	}
	//重载 !=号
	bool operator!=(Person &p)
	{
		if (this->m_age == p.m_age && this->m_name == p.m_name)
		{
			return 0;
		}
		return 1;
	}
	string m_name;
	int m_age;
private:
};

void test01()
{
	Person p1("Tom",18);
	Person p2("jerry", 18);
	
	if (p1 == p2)
	{
		cout << "p1和p2是相等的" << endl;
	}
	else
	{
		cout << "p1和p2是不相等的" << endl;
	}
	if (p1 != p2)
	{
		cout << "p1和p2是不相等的" << endl;
	}
	else
	{
		cout << "p1和p2相等的" << endl;
	}
}

int main() {
	test01();
	system("pause");
	return 0;
}
4.5.6函数调用运算符重载
  • 函数调用运算符()也可以重载
  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  • 仿函数没有固定写法。非常灵活
#include<iostream>
using namespace std;
#include<string>

class MyPrint
{
public:
	//重载函数调用运算符
	void operator()(string test)
	{
		cout << test << endl;
	}
private:
};
void Myprint02(string test)
{
	cout << test << endl;
}
void test01()
{
	MyPrint myprint;
	myprint("hello world");//由于使用起来非常类似于函数调用,因此称为仿函数
	Myprint02("hello world");
}
//仿函数非常灵活,没有固定的写法
//加法类
class MyAdd
{
public:
	int operator()(int num1,int num2)
	{
		return num1 + num2;
	}
};
void test02()
{
	MyAdd myadd;
	int ret = myadd(100, 100);
	cout << ret << endl;
	//匿名函数对象
	cout << MyAdd()(100, 100) << endl;
}
int main() {
	test02();
	system("pause");
	return 0;
}

4.6继承

继承是面向对象三大特性之一
有些类与类之间存在特殊的关系,例如下图中:

image-20220407144630955

我们发现,定义这些类时,下级别的成员除了拥有上一级的共性,还有自己的特性。

这个时候我们就可以考虑利用继承的技术,减少重复代码

例如我们看到很多网站中,都有公共的头部,公共的底部,甚至公共的左侧列表,只有中心内容不同

接下来我们分别利用普通写法和继承的写法来实现网页中的内容,看一下继承存在的意义以及好处

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

//普通实现页面
//Java页面
//class Java
//{
//public:
//	void header()
//	{
//		cout << "首页、公开课、登录、注册...(公共头部)" << endl;
//	}
//	void footer()
//	{
//		cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl;
//	}
//	void left() 
//	{
//		cout << "Java、python、C++、...(公共分类列表)" << endl;
//	}
//	void content()
//	{
//		cout << "Java学科视频" << endl;
//	}
//private:
//}; 
//class Python
//{
//public:
//	void header()
//	{
//		cout << "首页、公开课、登录、注册...(公共头部)" << endl;
//	}
//	void footer()
//	{
//		cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl;
//	}
//	void left()
//	{
//		cout << "Java、python、C++、...(公共分类列表)" << endl;
//	}
//	void content()
//	{
//		cout << "Python学科视频" << endl;
//	}
//private:
//};
//class CPP
//{
//public:
//	void header()
//	{
//		cout << "首页、公开课、登录、注册...(公共头部)" << endl;
//	}
//	void footer()
//	{
//		cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl;
//	}
//	void left()
//	{
//		cout << "Java、python、C++、...(公共分类列表)" << endl;
//	}
//	void content()
//	{
//		cout << "C++学科视频" << endl;
//	}
//private:
//};
class BasePage
{
public:
	void header()
	{
		cout << "首页、公开课、登录、注册...(公共头部)" << endl;
	}
	void footer()
	{
		cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl;
	}
	void left() 
	{
		cout << "Java、python、C++、...(公共分类列表)" << endl;
	}
private:
};
class Java :public BasePage
{
public:
	void content()
	{
		cout << "Java学科视频" << endl;
	}
};
class Python :public BasePage
{
public:
	void content()
	{
		cout << "Python学科视频" << endl;
	}
};
class CPP :public BasePage
{
public:
	void content()
	{
		cout << "C++学科视频" << endl;
	}
};
void test01()
{
	cout << "Java的下载视频如下:" << endl;
	Java ja;
	ja.header();
	ja.footer();
	ja.left();
	ja.content();
	cout << "--------------------" << endl;
	
	cout << "Python的下载视频如下:" << endl;
	Python py;
	py.header();
	py.footer();
	py.left();
	py.content();
	cout << "--------------------" << endl;
	
	cout << "C++的下载视频如下:" << endl;
	CPP cpp;
	cpp.header();
	cpp.footer();
	cpp.left();
	cpp.content();
}

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

继承的好处:减少重复代码

语法: class 子类 : 继承方式 父类

子类 也称为 派生类

父类 也称为 基类

派生类中的成员,包含两大部分:

一类是从基类继承过来的,一类是自己增加的成员。

从基类继承过过来的表现其共性,而新增的成员体现了其个性

4.6.2继承方式

继承的语法:class 子类 : 继承方式 父类

继承方式一共有三种:

  • 公共继承
  • 保护继承
  • 私有继承
image-20220407151153600
#include<iostream>
using namespace std;
#include<string>

class Base1
{
public:
	int m_a;
protected:
	int m_b;
private:
	int m_c;
};
class Son1 :public Base1
{
public:
	void func()
	{
		m_a = 10;//父类中的公共权限成员到子类中依然是公共权限
		m_b = 10;//父类中的保护权限成员到子类中依然是保护权限
		//m_c = 10;//父类中的私有权限成员子类访问不到
	}
};
void test01()
{
	Son1 s1;
	s1.m_a = 100;
	//s1.m_b = 100;//到Son1中 m_b是保护权限类外访问不到
}
class Son2 :protected Base1
{
public:
	void func()
	{
		m_a = 10;//父类中的公共权限成员到子类中变为保护权限
		m_b = 10;//父类中的保护权限成员到子类中依然是保护权限
		//m_c = 10;//父类中的私有权限成员子类访问不到
	}
};
void test02()
{
	Son2 s2;
	//s2.m_a = 100; //在Son2中 m_a变为保护权限,因此类外访问不到
	//s2.m_b = 100;//到Son2中 m_b是保护权限类外访问不到
}
class Son3 :private Base1
{
public:
	void func()
	{
		m_a = 10;//父类中的公共权限成员到子类中变为私有权限
		m_b = 10;//父类中的保护权限成员到子类中变为私有权限
		//m_c = 10;//父类中的私有权限成员子类访问不到
	}
};
void test03()
{
	Son3 s3;
	//s3.m_a = 100; //在Son2中 m_a变为私有权限,因此类外访问不到
	//s3.m_b = 100;//到Son2中 m_b是私有权限类外访问不到
}
class Grandson3 : public Son3
{
public:
	void func()
	{
		//m_a = 1000;//到了Son3中 m_A变为私有,及时是儿子,也是访问不到
		//m_B = 1000;//到了Son3中 m_B变为私有,及时是儿子,也是访问不到
	}
};
int main() {
	test01();
	system("pause");
	return 0;
}
4.6.3继承中的对象模型

问题:从父类继承过来的成员,哪些属于子类对象中?

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

//利用开发人员命令提示工具查看对象模型
//跳转盘符F:
//跳转文件路径cd具体路径下
//查看命名
//cl /d1 reportSingleClassLayoutSon "01 C++.cpp"
class Base
{
public:
	int m_A; 
protected:
	int m_B; 
private:
	int m_C;//私有成员只是被隐藏了,但是还是会继承下去		
};
// 公共继承
class Son :public Base
{
public:
	int m_D;
};
void test01() {
	//16
	// 父类中所有非静态成员属性都会被子类继承下去
	//父类中私有成员属性是被编译器给隐藏了,因此是访问不到,但是确实被继承下去了
	cout << "sizeof Son=" << sizeof(Son) << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
4.6.4继承中构造和析构顺序

子类继承父类后,当创建子类对象,也会调用父类的构造函数

问题:父类和子类的构造和析构阃序是谁先谁后?

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

class Base
{
public:
	Base()
	{
		cout << "Base的构造函数" << endl;
	}
	~Base()
	{
		cout << "Base的析构函数" << endl;
	}
};
// 公共继承
class Son :public Base
{
public:
	Son()
	{
		cout << "Son的构造函数" << endl;
	}
	~Son()
	{
		cout << "Son的析构函数" << endl;
	}
};
void test01() {
	//Base b;
	Son a;
}
int main() {
	test01();
	system("pause");
	return 0;
}

继承中的构造和析构顺序如下:

先构造父类,再构造子类,析构的顺序与构造的顺序相反

4.6.5继承同名成员处理方式

问题:当子类与父类出现同名的成员,如何通过子类对象,访问到子类或父类中同名的数据呢?

  • 访问子类同名成员直接访问即可
  • 访问父类同名成员需要加作用域
#include<iostream>
using namespace std;
#include<string>

class Base
{
public:
	Base()
	{
		m_a = 100;
	}
	void func()
	{
		cout << "Base - func()调用" << endl;
	}
	void func(int a)
	{
		cout << "Base - func()调用" << endl;
	}
	int m_a;
};
// 公共继承
class Son :public Base
{
public:
	Son()
	{
		m_a = 200;
	}
	void func()
	{
		cout << "Son - func()调用" << endl;
	}
	int m_a;
};
//同名成员属性处理
void test01() {
	//Base b;
	Son a;
	cout << "Son  下 m_a = " << a.m_a << endl;
	//如果通过子类对象访问到父类中同名成员,需要加作用域
	cout << "Base 下 m_a = " << a.Base::m_a << endl;
}
void test02()
{
	Son s;
	//s.func(); //直接调用调用是子类中的同名成员
	//如何调用到父类中同名成员函数?Ⅰ
	s.Base::func();
	//如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏掉父类中所有同名成员函数
	//如果想访问到父类中被隐藏的同名成员函数,需要加作用域
	s.Base::func(100);
}
int main() {
	test02();
	system("pause");
	return 0;
}

总结:
1.子类对象可以直接访问到子类中同名成员

2.子类对象加作用域可以访问到父类同名成员

3.当子类与父类拥有同名的成员函数,子类会隐藏父类中同名成员函数,加作用域可以访问到父类中同名函数

4.6.6继承同名静态成员处理方式

问题:继承中同名的静态成员在子类对象上如何进行访问?

静态成员和非静态成员出现同名,处理方式一致

  • 访问子类同名成员直接访问即可

  • 访问父类同名成员需要加作用域

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

class Base
{
public:
	static int m_a;
	static void func()
	{
		cout << "Base - static void func()" << endl;
	}
};
int Base::m_a = 100;
class Son :public Base
{
public:
	static int m_a;
	static void func()
	{
		cout << "Son - static void func()" << endl;
	}
};
int Son::m_a = 200;
//同名静态成员属性
void test01() {
	Son s;
	//1.通过对象访问
	cout << "Son  下的m_a = " << s.m_a << endl;
	cout << "Base 下的m_a = " << s.Base::m_a << endl;
	//2.通过类名访问
	cout << "通过类名访问:" << endl;
	cout << "Son下  m_a = " << Son::m_a << endl ;
	//第一个::代表通过类名方式访问第二个::代表访问父类作用域下
	cout << "Base下 m_a = " <<Son::Base::m_a<< endl ;

}
void test02() {
	Son s;
	//1.通过对象访问
	s.func();
	s.Base::func();
	//2.通过类名访问
	Son::func();
	Son::Base::func();
	// 子类出现和父类同名静态成员函数,也会隐藏父类中所有同名成员函数 / 如果想访问父类中被隐藏同名成员,需要加作用域
	//Son::Base::func(100);

}
int main() {
	test02();
	system("pause");
	return 0;
}
4.6.7多继承语法

C++允许一个类继承多个类

语法: class子类∶继承方式 父类1,继承方式 父类2…

多继承可能会引发父类中有同名成员出现,需要加作用域区分

C++实际开发中不建议用多继承

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

class Base1
{
public:
	Base1()
	{
		m_a = 100;
	}
	int m_a;
};
class Base2
{
public:
	Base2()
	{
		m_a = 200;
	}
	int m_a;
};
//
//子类需要继承Base1和Base2
class Son :public Base1, public Base2
{
public:
	Son() 
	{
		m_c = 300;
		m_d = 400;
	}
	int m_c;
	int m_d;
};
void test01() 
{
	Son s;
	cout << "sizeof Son = " << sizeof(s) << endl;
	//当父类中出现同名成员,需要加作用域区分
	cout << "Basel::m_A = " << s.Base1::m_a << endl;
	cout << "Base2::m_A = " << s.Base2::m_a << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
4.6.8菱形继承

菱形继承概念:

​ 两个派生类继承同一个基类

​ 又有某个类同时继承者两个派生类

​ 这种继承被称为菱形继承,或者钻石继承

典型的菱形继承案例:

image-20220407171714177

菱形继承问题:

  1. 羊继承了动物的数据,驼同样继承了动物的数据,当草泥马使用数据时,就会产生二义性。
  2. 草泥马继承自动物的数据继承了两份,其实我们应该清楚。这份数据我们只需要一份就可以。
#include<iostream>
using namespace std;
#include<string>

class Animal
{
public:
	int m_age;
};
//利用虚继承解决菱形继承的问题
//继承之前加上关键字virtual变为虚继承 
// Animal类称为虚基类
//羊类
class Sheep :virtual public Animal {};
//驼类
class Tuo :virtual public Animal {};
//羊驼类
class SheepTuo : public Sheep,public Tuo {};

void test01() 
{
	SheepTuo st;
	st.Sheep::m_age = 18;
	st.Tuo::m_age = 28;
	// 当菱形继承,两个父类拥有相同数据,需要加以作用域区分
	cout << "st.Sheep::m_age = " << st.Sheep::m_age << endl;
	cout << "st.Tuo::m_age = " << st.Tuo::m_age << endl;
	//这份数据我们知道只有有一份就可以,菱形继承导致数据有两份,资源浪费
	cout << "st.m_age = " << st.m_age << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
image-20220407173235274

4.7多态

4.7.1多态的基本概念

多态是C++面向对象三大特性之一

多态分为两类

  • 静态多态:函数重载和运算符重载属于静态多态,复用函敌名
  • 动态多态:派生类和虚函教实现运行时多态

静态多态和动态多态区别:

  • 静态多态的函数地址早绑定- 编译阶段确定函数地址
  • 动态多态的函教地址晚绑定- 运行阶段确定函数地址

下面通过案例进行讲解多态

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

//多态
//动物类
class Animal
{
public:
	//虚函数
	virtual void speak()
	{
		cout << "动物在说话" << endl;
	}
};
class Cat :public Animal
{
public:
	//重写函数返回值类型函数名参数列表完全相同
	//子类virtual关键字可写可不行,父类必须写
	void speak()
	{
		cout << "小猫在说话" << endl;
	}
};
class Dog :public Animal
{
public:
	void speak()
	{
		cout << "小狗在说话" << endl;
	}
};
//执行说话的函数
//地址早绑定在编译阶段确定函数地址
//如果想执行让猫说话,那么这个函数地址就不能提前绑定,需要在运行阶段进行绑定,地址晚绑定

//动态多态满足条件
// 1、有继承关系
// 2、子类 '重写' 父类的虚函数

//动态多态使用
//父类的指针或者引用  指向子类对象

void  doSpeak(Animal &animal) //Animal &animal=cat;
{
	animal.speak();
}
void test01() 
{
	Cat cat;
	doSpeak(cat);
	Dog dog;
	dog.speak();
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结:
多态满足条件

  • 有继承关系
  • 子类重写父类中的虚函数

多态使用条件

  • 父类指针或引用指向子类对象

重写:函数返回值类型函数名参数列表完全一致称为重写

image-20220407211038302
4.7.2多态案例- -计算器类

案例描述:

分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类

多态的优点:

  • 代码组织结构清晰
  • 可读性强
  • 利于前期和后期的扩展以及维护
#include<iostream>
using namespace std;
#include<string>

class Calculate
{
public:
	int getResult(string oper)
	{
		if (oper == "+")
		{
			return m_num1 + m_num2;
		}
		else if (oper == "-")
		{
			return m_num1 - m_num2;
		}
		else if (oper == "*")
		{
			return m_num1 * m_num2;
		}

	}
	//如果想扩展新的功能,需求修改源码
	//在真是开发中提倡开闭原则
	//开闭原则:对扩展进行开放,对修改进行关闭

	int m_num1;
	int m_num2;
};
//利用多态实现计算器
//多态好处:
//1. 组织结构清晰
//2、 可读性强
//3、 对于前期和后期扩展以及维护性高

//实现计算器抽象类
class AbstractCalculator
{
public:
	virtual int getResult()
	{
		return 0;
	}
	int m_num1;
	int m_num2;
};
//加法计算器类
class AddCalculator :public AbstractCalculator
{
public:
	int getResult()
	{
		return m_num1 + m_num2;
	}
};
//减法计算器类
class SubCalculator :public AbstractCalculator
{
public:
	int getResult()
	{
		return m_num1 - m_num2;
	}
};
//乘法计算器类
class MulCalculator :public AbstractCalculator
{
public:
	int getResult()
	{
		return m_num1 * m_num2;
	}
};
void test01() 
{
	Calculate c;
	c.m_num1 = 10;
	c.m_num2 = 10;
	cout << c.m_num1 << "+" << c.m_num2 << " = " << c.getResult("+") << endl;
	cout << c.m_num1 << "-" << c.m_num2 << " = " << c.getResult("-") << endl;
	cout << c.m_num1 << "*" << c.m_num2 << " = " << c.getResult("*") << endl;
}
void test02()
{
	AbstractCalculator *abc = new AddCalculator;
	abc->m_num1 = 100;
	abc->m_num2 = 100;
	cout << abc->m_num1 << " + " << abc->m_num2 << " = " << abc->getResult() << endl;
	//用完记得销毁
	delete abc;
	
	abc = new SubCalculator;
	abc->m_num1 = 100;
	abc->m_num2 = 100;
	cout << abc->m_num1 << " + " << abc->m_num2 << " = " << abc->getResult() << endl;
	//用完记得销毁
	delete abc;
	
	abc = new MulCalculator;
	abc->m_num1 = 100;
	abc->m_num2 = 100;
	cout << abc->m_num1 << " + " << abc->m_num2 << " = " << abc->getResult() << endl;
	//用完记得销毁
	delete abc;
}
int main() {
	//test01();
	test02();
	system("pause");
	return 0;
}
4.7.3纯虚函数和抽象类

在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容

因此可以将虚函数改为纯虚函数

纯虚函数语法: virtual 返回值类型 函数名(参数列表)=0

当类中有了纯虚函数,这个类也称为抽象类

抽象类特点:

  • 无法实例化对象
  • 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
#include<iostream>
using namespace std;
#include<string>

class Base
{
public:
	//纯虚函数
	//只要有一个纯虚函数,这个类称为抽象类
	//抽象类特点:
	//1.无法实例化对象
	//2.抽象类的子类必须重写抽象类中的纯虚函数,否则也属于抽象类
	virtual void func() = 0;
};
class Son :public Base
{
	virtual void func() 
	{
		cout << "func函数调用" << endl;
	}
};
void test01() 
{
	//Base b;	//抽象类无法实例化对象
	//new Base;	//抽象类无法实例化对象
	Base *base = new Son;
	base->func();
}
int main() {
	test01();
	system("pause");
	return 0;
}
4.7.4多态案例二-制作饮品

案例描述:

制作饮品的大致流程为:煮水-冲泡-倒入杯中-加入辅料

利用多态技术实现本案例,提供抽象制作饮品基类,提供子类制作咖啡和茶叶

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

class AbstractDrinking
{
public:
	//煮水
	virtual void Boil() = 0;
	//冲泡
	virtual void Brew() = 0;
	//倒入杯中
	virtual void PourInCup() = 0;
	//加入辅料
	virtual void PutSomething() = 0;
	//制作饮品
	void makeDrink()
	{
		Boil();
		Brew();
		PourInCup();
		PutSomething();
	}
};
class Coffee :public AbstractDrinking
{
public:
	//煮水
	virtual void Boil()
	{
		cout << "煮农夫山泉" << endl;
	}
	//冲泡
	virtual void Brew()
	{
		cout << "冲泡咖啡" << endl;
	}
	//倒入杯中
	virtual void PourInCup()
	{
		cout << "倒入杯中" << endl;
	}
	//加入辅料
	virtual void PutSomething()
	{
		cout << "加入糖和牛奶" << endl;
	}
};
class Tea :public AbstractDrinking
{
public:
	//煮水
	virtual void Boil()
	{
		cout << "煮矿泉水" << endl;
	}
	//冲泡
	virtual void Brew()
	{
		cout << "冲泡茶叶" << endl;
	}
	//倒入杯中
	virtual void PourInCup()
	{
		cout << "倒入杯中" << endl;
	}
	//加入辅料
	virtual void PutSomething()
	{
		cout << "加入枸杞" << endl;
	}
};
//制作
void doWork(AbstractDrinking *abs) 
{
	abs->makeDrink();
	delete abs;
}
void test01() 
{
	doWork(new Coffee);
	cout << "-----------------" << endl;
	doWork(new Tea);
}
int main() {
	test01();
	system("pause");
	return 0;
}
4.7.5虚析构和纯虚析构

多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时无法调用到子类的析构代码

解决方式:将父类中的析构函数改为虚析构或者纯虚析构

虚析构和纯虚析构共性:

  • 可以解决父类指针释放子类对象
  • 都需要有具体的函教实现

虚析构和纯虚析构区别:

  • 如果是纯虚析构,该类属于抽象类,无法实例化对象

虚析构语法:

virtual ~类名(){}

纯虚析构语法:

virtual ~类名()=0;

类名::~类名(){}

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

class Animal
{
public:
	Animal()
	{
		cout << "Animal构造函数调用" << endl;
	}
	//利用虚析构可以解决 父类指针释放子类对象时不干净的问题
	//virtual ~Animal()
	//{
	//	cout << "Animal析构函数调用" << endl;
	//}
	//纯虚析构 需要声明也需要实现
	//有了纯虚析构之后,这个类也属于抽象类,无法实例化对象
	virtual ~Animal() = 0;
	//纯虚函数
	virtual void speak() = 0;
};
Animal::~Animal()
{
	cout << "Animal纯析构函数调用" << endl;
}
class Cat :public Animal
{
public:
	Cat(string name)
	{
		cout << "Cat构造函数调用" << endl;
		m_name = new string(name);
	}
	~Cat()
	{
		if (m_name != NULL)
		{
			cout << "Cat析构函数调用" << endl;
			delete m_name;
			m_name = NULL;
		}
	}
	virtual void speak()
	{
		cout << *m_name << "小猫在说话" << endl;
	}
	string *m_name;
};
void test01() 
{
	Animal *animal = new Cat("Tom");
	animal->speak();
	//父类指针在析构时候不会调用子类中析构函数,导致子类如果有堆区属性,出现内存泄漏
	delete animal;
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结:

  • 虚析构或纯虚析构就是用来解决通过父类指针释放子类对象
  • 如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
  • 拥有纯虚析构函数的类也属于抽象类
4.7.6多态案例三-电脑组装

案例描述:

电简主要组成部件为CPU(用于计算),显卡(用于显示),内存条(用于存储)

将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商

创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口

测试时组装三台不同的电脑进行工作

image-20220408113527466
#include<iostream>
using namespace std;
#include<string>

class CPU
{
public:
	virtual void calculate() = 0;
};
class VideoCard
{
public:
	virtual void display() = 0;
};
class Memory
{
public:
	virtual void storage() = 0;
};
//电脑
class Computer
{
public:
	Computer(CPU *cpu, VideoCard *vc, Memory * mem)
	{
		m_cpu = cpu;
		m_vc = vc;
		m_mem = mem;
	}
	~Computer()
	{
		if (m_cpu != NULL)
		{
			delete m_cpu;
			m_cpu = NULL;
		}
		if (m_vc != NULL)
		{
			delete m_vc;
			m_vc = NULL;
		}
		if (m_mem != NULL)
		{
			delete m_mem;
			m_mem = NULL;
		}
	}
	void work()
	{
		m_cpu->calculate();
		m_vc->display();
		m_mem->storage();
	}
private:
	CPU * m_cpu;
	VideoCard * m_vc;
	Memory * m_mem;
};
class IntelCPU :public CPU
{
	virtual void calculate()
	{
		cout << "intel的CPU开始工作了" << endl;
	}
};
class IntelVideoCard :public VideoCard
{
	virtual void display()
	{
		cout << "intel的显卡开始工作了" << endl;
	}
};
class IntelMemory :public Memory
{
	virtual void storage()
	{
		cout << "intel的内存条开始工作了" << endl;
	}
};
class LenovoCPU :public CPU
{
	virtual void calculate()
	{
		cout << "Lenovo的CPU开始工作了" << endl;
	}
};
class LenovoVideoCard :public VideoCard
{
	virtual void display()
	{
		cout << "Lenovo的显卡开始工作了" << endl;
	}
};
class LenovoMemory :public Memory
{
	virtual void storage()
	{
		cout << "Lenovo的内存条开始工作了" << endl;
	}
};
void test01() 
{
	//第一台电脑零件
	CPU *intelCpu = new IntelCPU;
	VideoCard * intelCard = new IntelVideoCard;
	Memory *intelMem = new IntelMemory;

	//创建第一台电脑
	Computer * computer1 = new Computer(intelCpu, intelCard, intelMem);
	computer1->work();
	delete computer1;

	cout << "--------------------" << endl;
	Computer * computer2 = new Computer(new LenovoCPU, new LenovoVideoCard, new LenovoMemory);
	computer2->work();
	delete computer2;

	cout << "--------------------" << endl;
	Computer * computer3 = new Computer(new IntelCPU, new LenovoVideoCard, new LenovoMemory);
	computer3->work();
	delete computer3;
}
int main() {
	test01();
	system("pause");
	return 0;
}

5文件操作

程序运行时产生的数据都属于临时数据,程序—旦运行结束都会被释放

通过文件可以将数据持久化

C++中对文件操作需要包含头文件< fstream >

文件类型分为两种:

  1. 文本文件:文件以文本的AScII码形式存储在计算机中
  2. 二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们

操作文件的三大类:

  1. ofstream:写操作
  2. ifstream:读操作
  3. fstream:读写操作

5.1 文本文件

5.1.1写文件

写文件步骤如下:

  1. 包含头文件 #include
  2. 创建流对象 ofstream ofs;
  3. 打开文件 ofs.open(文件路径".打开方式);
  4. 写数据 ofs <<“写入的数据”;
  5. 关闭文件 ofs.close();

文件打开方式:

image-20220408151942636

注意:文件打开方式可以配合使用,利用|操作符

例如:用二进制方式写文件ios::binary | ios::out

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

void test01()
{
	ofstream ofs;

	ofs.open("text.txt", ios::out);

	ofs << "张三" << endl;

	ofs << "18岁" << endl;

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

总结:

  • 文件操作必须包含头文件fstream
  • 读文件可以利用ofstream ,或者fstream类
  • 打开文件时候需要指定操作文件的路径,以及打开方式
  • 利用<<可以向文件中写数据
  • 操作完毕,要关闭文件
5.1.2读文件

读文件与写文件步骤相似,但是读取方式相对于比较多

读文件步骤如下:

  1. 包含头文件 #include

  2. 创建流对象 ifstream ifs;

  3. 打开文件并判断文件是否打开成功

    ifs.open(“文件路径”.打开方式);

  4. 读数据 四种方式读取

  5. 关闭文件 ifs.close();

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

void test01()
{
	ifstream ifs;

	ifs.open("text.txt", ios::in);

	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}
	//1.第一种
	//char buf[1024] = { 0 };
	//while (ifs >> buf)
	//{
	//	cout << buf << endl;
	//}

	//第二种
	//char buf[1024] = { 0 };
	//while (ifs.getline(buf,sizeof(buf)))
	//{
	//	cout << buf << endl;
	//}

	//第三种
	//string buf;
	//while (getline(ifs,buf))
	//{
	//	cout << buf << endl;
	//}

	//第四种
	char c;
	while ((c = ifs.get()) != EOF)
	{
		cout << c;
	}
	ifs.close();
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结:

  • 读文件可以利用 ifstream ,或者fstream类

  • 利用is_open函数可以判断文件是否打开成功

  • close关闭文件

  • 用第三种

string buf;
while (getline(ifs,buf))
{
	cout << buf << endl;
}

5.2二进制文件

以二进制的方式对文件进行凌写操怍打开方式要指定为ios::binary

5.2.1写文件

二进制方式写文件主要利用流对象调用成员函数write

函数原型:ostrean& write(const char * buffer ,int len);

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

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

class Person
{
public:
	char m_name[64];
	int m_age;
};
void test01()
{
	ofstream ofs("person.txt", ios::binary | ios::out);
	//ofs.open("person.tet", ios::binary | ios::out);
	Person p = { "张三",18 };
	ofs.write((const char *)&p, sizeof(Person));
	ofs.close();
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结:

  • 文件输出流对象可以通过write函数,以二进制方式写数据
5.2.2读文件

二进制方式读文件主要利用流对象调用成员函数read函数

原型: istream& read(char *buffer,int len);

参数解释:字宁符指针buffer指向内存中—段存储空间。len是读写的字节数

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

class Person
{
public:
	char m_name[64];
	int m_age;
};
void test01()
{
	ifstream ifs("person.txt", ios::binary | ios::in);
	if (!ifs.is_open())
	{
		cout << "打开失败" << endl;
	}
	Person p;
	ifs.read((char*)&p, sizeof(Person));
	cout << "姓名: " << p.m_name << "  年龄: " << p.m_age << endl;
	ifs.close();
}
int main() {
	test01();
	system("pause");
	return 0;
}

6.模板

6.2函数模板

  • C++另一种编程思想称为泛型编程,主要利用的技术就是模板
  • C++提供两种模板机制:函数模板类模板
6.2.1函数模板语法

函数模板作用:

建立一个通用函数,其函数返回值类型和形参类型可以不具体制定,用一个虚拟的类型来代表。

语法:

template<typename T>
函数声明或定义

解释:
template —声明创建模板

typename —表面其后面的符号是一种数据类型,可以用class代替

T —通用的数据类型,名称可以替换,通常为大写字母

#include<iostream>
using namespace std;

//函数模板

//交换两个整型函数
void swapInt(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}
//交换两个浮点型函数
void swapDouble(double &a,double &b)
{
	double temp = a;
	a = b;
	b = temp;
}
//函数模板
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;
	//swapInt(a, b);
	//利用函数模板交换
	//两种方式使用函数模板
	//1、自动类型推导
	//mySwap(a,b);
	
	// 2、显示指定类型
	mySwap<int>(a,b);
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结:

  • 函数模板利用关键字template
  • 使用函数模板有两种方式:自动类型推导、显示指定类型
  • 模板的目的是为了提高复用性,将类型参数化
6.2.2函数模板注意事项

注意事项:

  • 自动类型推导,必须推导出一致的数据类型T,才可以使用
  • 模板必须要确定出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;
}
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<int>();
}
int main() {
	test01();
	test02();
	system("pause");
	return 0;
}
6.2.3函数模板案例

案例描述:

  • 利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序。
  • 排序规则从大到小,排序算法为选择排序
  • 分别利用char数组和int数组进行测试
#include<iostream>
using namespace std;

//实现通用对数组进行排序的函数/规则从大到小
//算法选择
//测试char数组、int数组
//排序算法
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)
		{
			mySwap(arr[max], arr[i]);
		}
	}
}
template<class T>
void mySwap(T &a, T &b)
{
	T temp = a;
	a = b;
	b = temp;
}
//提供打印数组模板
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;
}
6.2.4普通函数与函数模板的区别

普通函数与函数模板区别:

  • 普通函数调用时可以发生自动类型转换(隐式类型转换)
  • 函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
  • 如果利用显示指定类型的方式,可以发生隐式类型转换
#include<iostream>
using namespace std;

//普通函数与函数模板区别
//1、普通函数调用可以发生隐式类型转换
//2、函数模板用自动类型推导,不可以发生隐式类型转换
//3、函数模板用显示指定类型,可以发生隐式类型转换

//普通函数
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;//c->97

	//自动类似推导	不会发生隐式类型转换
	//cout << myAdd02(a,c) << endl;

	//显示指定类型	会发生隐式类型转换
	cout << myAdd02<int>(a, c) << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
6.2.5普通函数与函数模板的调用规则

调用规则如下:

  1. 如果函数模板和普通函数都可以实现。优先调用普通函数
  2. 可以通过空模板参数列表来强制调用函数模板
  3. 函数模板也可以发生重载
  4. 如果函数模板可以产生更好的匹配,优先调用函数模板
#include<iostream>
using namespace std;

//普通函数
void myPrint(int a, int b)
{
	cout << "调用的普通函数" << endl;
}
template<class T>
void myPrint(T a, T b)
{
	cout << "调用的模板" << endl;
}
template<class T>
void myPrint(T a, T b,T c)
{
	cout << "调用的函数模板" << endl;
}
void test01()
{
	int a = 10;
	int b = 20;
	char c = 'c';
	
	//myPrint(a, b); //优先调用普通函数,若普通函数没有函数实现则编译器报错

	//通过空模板参数列表,强制调用函数模板
	//myPrint<>(a, b);

	//myPrint(a, b, 100);

	//如果函数模板产生更好的匹配,优先调用函数模板
	char c1 = 'c';
	char c2 = 'c';
	myPrint(c1, c2);
}
int main() {
	test01();
	system("pause");
	return 0;
}
6.2.6模板的局限性

局限性:

模板的通用性并不是万能的

image-20220413165350705
#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", 10);
	bool ret = myCompare(p1, p2);
	if (ret)
	{
		cout << "p1 == p2" << endl;
	}
	else
	{
		cout << "p1 != p2" << endl;
	}
}
int main() {
	//test01();
	test02();
	system("pause");
	return 0;
}

总结:

  • 利用具体化的模板,可以解决自定义类型的通用化I
  • 学习模板并不是为了写模板,而是在STL能够运用系统提供的模板

6.3类模板

6.3.1类模板语法类模板

作用:

  • 建立一个通用类,类中的成员数据类型可以不员体制定,用一个虚拟的类型来代表。
template<typename 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 = "<< m_name <<" age = "<< 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后面加类,此类称为类模板

6.3.2类模板与函数模板区别

类模板与函数楼板区别主要有两点:

  1. 类模板没有自动类型推导的使用方式
  2. 类模板在模板参数列表中可以有默认参数
#include<iostream>
using namespace std;
#include<string>

template<class NameType=string,class AgeType=int>
class Person
{
public:
	Person(NameType name, AgeType age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	void showPerson()
	{
		cout <<"name = "<< m_name <<" age = "<< m_age << endl;
	}
	NameType m_name;
	AgeType m_age;
};
//1. 类模板没有自动类型推导的使用方式

void test01()
{
	//Person p("孙悟空", 1000); 无法用自动类型推导
	Person<string, int>p1("孙悟空", 1000);//只能用显示指定类型
	p1.showPerson();
}
//2. 类模板在模板参数列表中可以有默认参数
void test02()
{
	Person<> p("猪八戒", 999);
	p.showPerson();
}
int main() {
	//test01();
	test02();
	system("pause");
	return 0;
}
6.3.3类模板中成员函数创建时机

类模板中成员函数和普通类中成员函数创建时机是有区别的:

  • 普通类中的成员函数一开始就可以创建
  • 类模板中的成员函数在调用时才创建
#include<iostream>
using namespace std;
#include<string>

class Person1
{
public:
	void showPerson1()
	{
		cout <<"Person1 show "<< endl;
	}
};
class Person2
{
public:
	void showPerson1()
	{
		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();
}
int main() {
	test01();
	//test02();
	system("pause");
	return 0;
}
6.3.4类模板对象做函数参数

学习目标:

  • 类模板实例化出的对象,向函数传参的方式

—共有三种传入方式:

  1. 指定传入的类型 —直接显示对象的数据类型
  2. 参数模板化 —将对象中的参数变为模板进行传递
  3. 整个类模板化 —将这个对象类型模板化进行传递
#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 << "name = " <<this-> m_name << " age = " << 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 << "T2的类型为:" << typeid(T2).name() << endl;
}
void test02()
{
	Person<string, int>p("猪八戒", 90);
	printPerson2(p);
}
//3、整个类模板化
template<class T>
void printPerson3(T &p)
{
	p.showPerson();
	cout << "T1的类型为:" << typeid(T).name() << endl;
}
void test03()
{
	Person<string, int>p("唐僧", 30);
	printPerson3(p);
}
int main() {
	//test01();
	//test02();
	test03();
	system("pause");
	return 0;
}
6.3.5类模板与继承

当类模板碰到继承时,需要注意一下几点:

  • 当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型
  • 如果不指定,编译器无法给子类分配内存
  • 如果想灵活指定出父类中T的类型,子类也需变为类模板
#include<iostream>
using namespace std;
#include<string>

template<class T>
class Base
{
public:
	T m;
};
//class Son :public Base//错误,必须知道父类中的T类型,才能继承给子类
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 test02()
{
	Son2<int, char>S2;
}
int main() {
	test01();
	test02();
	system("pause");
	return 0;
}
6.3.6类模板成员函数类外实现

学习目标:能够掌握类模板中的成员函数类外实现

#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();
	//test02();
	system("pause");
	return 0;
}
6.3.7类模板分文件编写

学习目标:

  • 掌握类模板成员函数分文件编写产生的问题以及解决方式

问题:

  • 类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到

解决:

  • 解决方式1∶直接包含.cpp源文件
  • 解决方式2∶将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称,并不是强制

main.cpp:

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

//第一种解决方式,直接包含 源文件
//#include"person.cpp"

//第二种解决方法,将.h和.cpp中的内容写到一起,将后缀名改为.hpp文件
#include"person.hpp"

void test01()
{
	Person<string, int>p("tom", 20);
	p.showPerson();
}
int main() {
	test01();
	system("pause");
	return 0;
}

person.hpp:

#pragma once
#include<iostream>
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;
}
6.3.8类模板与友元

学习目标:

  • 掌握类模板配合友元函数的类内和类外实现

全局函数类内实现-直接在类内声明友元即可
全局函数类外实现–需要提前让编译器知道全局函数的存在

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

template<class T1, class T2>
class Person;

//通过全局函数 打印Person信息
template<class T1, class T2>
void printPerson2(Person<T1, T2>p)
{
	cout << "类外实现---姓名: " << p.m_name << " 年龄:" << p.m_age << endl;
}
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);
private:
	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;
}
//全局函数在类内实现
void test01()
{
	Person<string, int>p("tom", 20);
	printPerson(p);
}
//全局函数在类外实现
void test02()
{
	Person<string, int>p2("jerry", 20);
	printPerson2(p2);
}
int main() {
	//test01();
	test02();
	system("pause");
	return 0;
}
6.3.9类模板案例

案例描述:实现一个通用的数组类,要求如下:

  • 可以对内置数据类型以及自定义数据类型的数据进行存储·
  • 将数组中的数据存储到堆区
  • 构造函数中可以传入数组的容量
  • 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
  • 提供尾插法和尾删法对数组中的数据进行增加和册除可以
  • 通过下标的方式访问数组中的元素
  • 可以获取数组中当前元素个数和数组的容量
image-20220419202317592

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);
	//MyArray<int>arr2(arr1);
	//MyArray<int>arr3(100);
	//arr3 = arr1;
	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;

	MyArray<int>arr2(arr1);
	//尾删
	arr2.Pop_Back();
	printIntArray(arr2);
	cout << "arr2的容量为: " << arr2.getCapacity() << endl;
	cout << "arr2的大小为: " << arr2.getSize() << endl;
}
//测试自定义数据类型
class Person
{
public:
	Person() {};
	Person(string name,int age) 
	{
		this->m_name = name;
		this->m_age = age;
	};
	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("孙悟空", 999);
	Person p2("韩信", 30);
	Person p3("妲己", 25);
	Person p4("赵云", 20);
	Person p5("安其拉", 27);

	arr.Push_Back(p1);
	arr.Push_Back(p2);
	arr.Push_Back(p3);
	arr.Push_Back(p4);
	arr.Push_Back(p5);

	printPersonArray(arr);
}
int main() {
	//test01();
	test02();
	system("pause");
	return 0;
}

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 = 防止浅拷贝问题 a=b=c
	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];
		//将arr中的数据都拷贝过来
		for (int i = 0; i < this->m_size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
		return *this;
	}
	~MyArray()
	{
		//cout << "MyArray析构函数调用" << endl;
		if (this->pAddress != NULL)
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
		}
	}
	//尾插法
	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--;
	}
	//通过下标方式访问数组中的元素arr[0] = 100
	T& operator[](int index)
	{
		return this->pAddress[index];
	}
	//返回数组容量
	int getCapacity()
	{
		return this->m_capacity;
	}
	//返回数组大小
	int getSize()
	{
		return this->m_size;
	}
private:
	T * pAddress;//指针指向堆区开辟的真实数组
	int m_capacity;//数组容量
	int m_size;//数组大小
};
	

2.STL初识

2.1 STL的诞生

  • 长久以来,软件界一直希望建立—种可重复利用的东西
  • C++的面向对象泛型编程思想,目的就是复用性的提升
  • 大多情况下,数据结构和算法都未能有一套标准,导致被迫从事大量重复工作
  • 为了建立数据结构和算法的一套标准,诞生了STL

2.2 STL基本概念

  • STL(Standard Template Library,标准模板库)
  • STL从广义上分为:容器(container)算法(algorithm)迭代器(iterator)。
  • 容器算法之间通过迭代器进行无缝连接。
  • STL几乎所有的代码都采用了模板类或者模板函教

2.3 STL六大组件

STL大体分为六大组件,分别是:容器、算法、迭代器、仿函数、适配器(配接器)、空间配置器

  1. 容器:各种数据结构,如vector、list.deque、set、map等,用来存放数据。
  2. 算法:各种常用的算法,如sort、find、copy、for_each等
  3. 迭代器:扮演了容器与算法之间的胶合剂。
  4. 仿函故:行为类似函数。可作为算法的某种策略。
  5. 适配器:—种用来修饰容器或者仿函教或迭代器接口的东西。
  6. 空间配置器:负责空间的配置与管理。

2.4 STL中容器、算法、迭代器

容器:置物之所也

STL容器就是将运用最广泛的一些数据结构实现出来

常用的数据结构:数组,链表,树,栈,队列,集合,映射表 等

这些容器分为序列式容器关联式容器两种:

序列式容器:强调值的排序,序列式容器中的每个元素均有固定的位置。

关联式容器:二叉树结构,各元素之间没有严格的物理上的顺序关系

算法:问题之解法也
有限的步骤,解决逻辑或数学上的问题,这一门学科我们叫做算法(Algorithms)

算法分为:质变算法非质变算法

质变算法:是指运算过程中会更改区间内的元素的内容。例如拷贝,替换,删除等等

非质变算法:是指运算过程中不会更改区间内的元素内容,例如查找、计数、遍历、寻找极值等等

迭代器种类

image-20220420153441775

常用的容器中迭代器种类为双向迭代器,和随机访问迭代器

2.5容器算法迭代器初识

了解STL中容器、.算法、迭代器概念之后,我们利用代码感受STL的魅力

STL中最常用的容器为Vector,可以理解为数组,下面我们将学习如何向这个容器中插入数据、并遍历这个容器

2.5.1 vector存放内置数据类型

容器: vector
算法: for_each
迭代器: vector<int>: :iterator

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

void myPrint(int val)
{
	cout << val << endl;
}
//vector容器存放内置数据类型
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;
}

2.5.2 vector存放自定义数据类型

学习目标:vector中存放自定义数据类型,并打印输出

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

class Person
{
public:
	Person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	string m_name;
	int m_age;
};
void test01()
{
	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).m_name << (*it).m_age << endl;
		cout << it->m_name << it->m_age << endl;
	}
}
int main() {
	test01();
	system("pause");
	return 0;
}

2.5.3 vector容器嵌套容器

学习目标:容器中嵌套宕器,我们将所有数据进行遍历输出

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

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++)
	{
		for (vector<int>::iterator vit = (*it).begin(); vit != (*it).end(); vit++)
		{
			cout << *vit << " ";
		}
		cout << endl;
	}
}
int main() {
	test01();
	system("pause");
	return 0;
}

3.STL-常用容器

3.1 string容器

3.1.1 string基本概念

本质:

  • string是C++风格的字符串,而string本质上是一个类

string和char区别:

  • char*是一个指针
  • string是一个类,类内部封装了char**,管理这个字符串,是一个char*型的容器。

特点:
string类内部封装了很多成员方法

例如:查找find,拷贝copy,删除delete替换replace,插入insert

string管理char*所分配的内存,不用担心复制越界和取值越界等,由类内部进行负责

3.1.2 string构造函数

构造函数原型:

  • string(); //创建一个空的字符串例如: string str;
    string(const char* s);//使用字符串s初始化
  • string(const string& str);//使用一个string对象初始化另一个string对象
  • string(int n, char c);//使用n个字符c初始化
#include<iostream>
using namespace std;
#include<string>

// string的构造函数
/*
string() ;					//创建一个空的字符串例如: string str;
string(const char* s);			//使用字符串s初始化
string(const string& str);	//使用一个string对象初始化另一个string对象
string(int n,char c) ;		//使用n个字符c初始化
*/
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的多种构造方式没有可比性,灵活使用即可

3.1.3 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的幅值操作
/*
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赋给当前字符串
*/
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;
}

3.1.4 string字符串拼接

功能描述:

  • 实现在字符串末尾拼接字符串

函数原型:

  • 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的幅值操作
    /*
    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个字符连接到字符串结尾
    */
    void test01()
    {
    	string str1 = "我";
    	str1 += "爱学习";
    	cout << "str1 = " << str1 << endl;
    	
    	str1 += ':';
    	cout << "str1 = " << str1 << endl;
    	
    	string str2="C++ python";
    	str1 += str2;
    	cout << "str1 = " << str1 << endl;
    	
    	string str3 = "I";
    	str3.append(" love ");
    	cout << "str3 =" << str3 << endl;
    	
    	str3.append("game abcde",4);
    	cout << "str3 =" << str3 << endl;
    	
    	//str3.append(str2);
    	cout << "str3 = " << str3 << endl;
    
    	str3.append(str2,4,6);//从第4个截取6个
    	cout << "str3 = " << str3 << endl;	
    }
    int main() {
    	test01();
    	system("pause");
    	return 0;
    }
    

3.1.5 string查找和替换

功能描述:

  • 查找:查找指定字符心是否存在
  • 替换:在指定的位置替换字符串

函数原型:

  • int find(const string& str, int pos = 0) const; //查找str第一次出现位置,从pos开始查找
  • int find(const char* s , int pos - e) const; //查找s第一次出现位置,从pos开始查找
  • int find(const char* s , int pos, int n) const; //从pos位置查找s的前n个字符第一次位置
  • int find(const char c, int pos = e) 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>

//字符串查找和替换

//1.查找
void test01()
{
	string str1 = "abcdefgde";
	int pos = str1.find("de");
	if (pos == -1)
	{
		cout << "未找到字符串" << endl;
	}
	else 
	{
		cout << "找到字符串,pos = " << pos << endl;
	}
	//rfind和find区别
	//rfind从右往左查找		find从左往右查找   序号都是从左边开始
	pos = str1.rfind("de");
	cout << "pos = " << pos << endl;
}

//2.替换
void test02()
{
	string str1 = "abcdefg";
	//从1号位置起3个字符替换为"1111"
	str1.replace(1,3, "1111");
	cout << "strl =" << str1 << endl;
}
int main() {
	//test01();
	test02();
	system("pause");
	return 0;
}

3.1.6 string字符串比较

功能描述:

  • 字符串之间的比较

比较方式:

  • 字符串比较是按字符的ASC!I码进行对比
    = 返回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 = "xello";

	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;
}

总结:字符串对比主要是用于比较两个字符串是否相等,判断谁大谁小的意义并不是很大

3.1.7 string字符存取

string中单个字符存取方式有两种

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

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

//string字符存取
void test01()
{
	string str = "hello";

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

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

	//修改单个字符
	str[0] = 'x';
	cout << "str = " << str << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结: string字符串中单个字符存取有两种方式,利用[]或at

3.1.8 string插入和删除

功能描述:

  • 对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个字符
#include<iostream>
using namespace std;
#include<string>

//字符串  插入和删除
void test01()
{
	string str = "hello";

	//插入
	str.insert(1, "111");
	cout << "str = " << str << endl;

	//删除
	str.erase(1, 3);
	cout << "str = " << 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 << "str = " << str << endl;
	cout << "subStr = " << subStr << endl;
}
//实用操作
void test02()
{
	string email = "zhangsan@sina.com";
	//从邮件地址中获取用户名信息

	int pos = email.find('@');
	string user = email.substr(0, pos);
	cout << "user = " << user << endl;
}
int main() {
	//test01();
	test02();
	system("pause");
	return 0;
}

3.2 vector容器

3.2.1 vector基本概念

功能:

  • vector数据结构和数组非常相似,也称为单端数组

vector与普通数组区别:

  • 不同之处在于数组是静态空间,而vector可以动态扩展

动态扩展:

  • 并不是在原空间之后续接新空间,而是找更大的内存空间,然后将原数据拷贝新空间,释放原空间
image-20220423162323809
  • vector容器的迭代器是支持随机访问的迭代器

3.22 vector构造函数

功能描述:

  • 创建vector容器

函数原型:

  • vector<T> v; //采用模板实现类实现,默认构造函数
  • vector(v.begin(), v.end()); //将vbegin(), end())区间中的元素拷贝给本身
  • vector(n,elem); //构造函数将n个elem拷贝给本身。
  • vector( const vector &vec ) ; //拷贝构造函数。
#include<iostream>
using namespace std;
#include<vector>

void printVector(vector<int>&v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 
	{
		cout << *it << " ";
	}
	cout << endl;
}
//vector容器构造
void test01()
{
	vector<int>v1;//默认构造  无参构造

	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	printVector(v1);

	//通过区间方式进行构造
	vector<int>v2(v1.begin(), v1.end()); 
	printVector(v2);
	
	//n个elem方式构造
	vector<int>v3(10,100); 
	printVector(v3);

	//拷贝构造
	vector<int>v4(v3); 
	printVector(v4);
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结: vector的多种构造方式没有可比性,灵活使用即可

3.2.3 vector赋值操作

功能描述:

  • 给vector容器进行赋值

函数原型:

  • vector& operator=(const vector &vec); //重载等号操作符

  • assign(beg,end) ; //将[beg, end)区间中的数据拷贝赋值给本身。

  • assign(n,elem); //将n个elem拷贝赋值给本身。

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

void printVector(vector<int>&v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 
	{
		cout << *it << " ";
	}
	cout << endl;
}
//vector赋值
void test01()
{
	vector<int>v1;//默认构造  无参构造

	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	printVector(v1);
	
	// 赋值	operator=
	vector <int>v2; 
	v2 = v1;
	printVector(v2);
	
	//assign
	vector<int>v3;
	v3.assign(v1.begin(),v1.end()); 
	printVector(v3);
	
	//n个elem方式赋值
	vector<int>v4;
	v4.assign(19,100); 
	printVector(v4);

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

总结: vector赋值方式比较简单,使用operator=,或者assign都可以

3.2.4 vector容量和大小

功能描述:

  • 对vector容器的容量和大小操作

函数原型:

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

  • capacity(); //容器的容量

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

  • resize(int num); //重新指定容器的长度为num,若容器变长,则以默认值填充新位置。

    ​ //如果容器变短,则末尾超出容器长度的元素被删除。

  • resize(int num,elem); //重新指定容器的长度为num,若容器变长,则以elem值填充新位置。
    //如果容器变短,则末尾超出容器长度的元素被删除

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

void printVector(vector<int>&v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 
	{
		cout << *it << " ";
	}
	cout << endl;
}
//vector容器的容量和大小操作
void test01()
{
	vector<int>v1;//默认构造  无参构造

	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	printVector(v1);
	
	if (v1.empty())//为真代表容器为空
	{
		cout << "v1为空" << endl;
	}
	else 
	{
	cout << "v1不为空" << endl;
	cout << "v1的容量为:" << v1.capacity() << endl;
	cout << "v1的大小为:" << v1.size() << endl;
	}

	//重新指定大小
	v1.resize(15, 100);//利用重载版本,可以指定默认填充值,参数2
	printVector(v1);//如果重新指定的比原来长了,默认用0填充新的位置
	
	v1.resize(5);
	printVector(v1);//如果重新指定的比原来短了,超出部分会删除掉
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结:

  • 判断是否为空— empty
  • 返回元素个数— size
  • 返回容器容量— capacity
  • 重新指定大小 — resize

3.2.5 vector插入和删除

功能描述:

  • 对vector容器进行插入、删除操作

函数原型:

  • push_back(ele); //尾部插入元素ele

  • pop_back() ; //删除最后一个元素

  • insert(const_iterator pos, ele); //迭代器指向位置pos插入元素ele

  • insert(const_iterator pos, int count,ele);//迭代器指向位置pos插入count个元素

  • eleerase(const_iterator pos); //删除迭代器指向的元素

  • erase(const_iterator start, const_iterator end);//删除迭代器从start到end之间的元素

  • clear(); //删除容器中所有元素

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

void printVector(vector<int>&v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 
	{
		cout << *it << " ";
	}
	cout << endl;
}
//vector容器的容量和大小操作
void test01()
{
	vector<int>v1;
	//尾插
	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(30);
	v1.push_back(40);
	v1.push_back(50);
	//遍历
	printVector(v1);
	//尾删
	v1.pop_back();
	printVector(v1);
	
	//插入第一个参数是迭代器
	v1.insert(v1.begin(),100) ;
	printVector(v1);

	v1.insert(v1.begin(),2,1000); 
	printVector(v1);
	
	//删除参数也是迭代器
	v1.erase(v1.begin());
	printVector(v1);

	//清空
	//v1.erase(v1.begin(),_v1.end() ) ;
	v1.clear();
	printVector(v1);
}
int main() {
	test01();
	system("pause");
	return 0;
}

总结:

  • 尾插— push_back
  • 尾删— pop_back
  • 插入— insert(位置迭代器)
  • 删除— erase(位置迭代器)
  • 清空— clear

3.2.6 vector数据存取

功能描述:

  • 对vector中的数据的存取操作

函数原型:

  • at(iht idx); //返回索引idx所指的数据
  • operator[]; //返回索引idx所指的数据
  • front( ); //返回容器中第一个数据元素
  • back(); //返回容器中最后一个数据元素
#include<iostream>
using namespace std;
#include<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;
}

3.2.7 vector互换容器

功能描述:

  • 实现两个容器内元素进行互换

函数原型:

  • wap(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 i = 10; i > 0; i--)
	{
		v2.push_back(i);
	}
	printVector(v2);
	
	cout << "交换后: " << endl;
	v1.swap(v2);
	printVector(v1);
	printVector(v2);
}
//2、实际用途
//巧用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);//用v初始化匿名对象,再交换回v
	cout << "v的容量为:" << v.capacity() << endl;
	cout << "v的大小为:" << v.size() << endl;
}
int main() {
	//test01();
	test02();
	system("pause");
	return 0;
}

总结: swap可以使两个容器互换,可以达到实用的收缩内存效果

3.2.8 vector预留空间

功能描述:

  • 减少vector在动态扩展容量时的扩展次数

函数原型:

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

void test01()
{
	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 = " << num << endl;
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

总结:如果数据量较大,可以一开始利用reserve预留空间

3.3 deque容器

3.3.1 deque容器基本概念

功能:

  • 双端数组,可以对头端进行插入删除操作

deque与vector区别:

  • vector对于头部的插入删除效率低,数据量越大,效率越低.
  • deque相对而言,对头部的插入删除速度回比vector快
  • vector访问元素时的速度会比deque快,这和两者内部实现有关
image-20220424112214719

deque内部工作原理:

deque内部有个中控器,维护每段缓冲区中的内容,缓冲区中存放真实数据中控器维护的是每个缓冲区的地址,使得使用deque时像一片连续的内存空间

image-20220424112519753
  • deque容器的迭代器也是支持随机访问的

3.3.2 deque构造函数

功能描述:

  • deque容器构造

函数原型:

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

void printDeque(const deque<int>&d) //限制只读
{
	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
		cout << *it << " ";	
	}
	cout << endl;
}
//deque构造函数
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);

	deque<int>d4(d3);
	printDeque(d4);
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

总结: deque容器和vector容器的构造方式几乎一致,灵活使用即可

3.3.3 deque赋值操作

功能描述:

  • 给deque容器进行赋值

函数原型:

  • deque& operator=(const deque &deq); //重载等号操作符
  • assign(beg,end); //将[beg, end)区间中的数据拷贝赋值给本身。
  • assign(n,elem); //将n个elem拷贝赋值给本身。
#include<iostream>
using namespace std;
#include<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;
}

和vector容器的几乎一致

3.3.4 deque大小操作

功能描述:

  • 对deque容器的大小进行操作

函数原型:

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

void printDeque(const deque<int>&d) //限制只读
{
	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
		cout << *it << " ";	
	}
	cout << endl;
}
//deque容器大小操作
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); 
	d1.resize(15,1); 
	printDeque(d1);

	d1.resize(5); 
	printDeque(d1);
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

3.3.5 deque插入和删除

功能描述:

  • 向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>

void printDeque(const deque<int>&d) //限制只读
{
	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
		cout << *it << " ";	
	}
	cout << endl;
}
//deque容器插入和删除
void test01()
{
	deque<int>d1;
	
	//尾插
	d1.push_back(10); 
	d1.push_back(20);
	
	//头插
	d1.push_front(100); 
	d1.push_front(200); 
	
	// 200 100 10 20
	printDeque(d1);

	//尾删
	d1.pop_back();
	//200 100 10
	printDeque(d1) ;
	
	//头删
	d1.pop_front();
	// 100 10
	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);
	//1000 200 100 10 20
	printDeque(d1);
	
	d1.insert(d1.begin(),2,10000);
	// 10000 10000 1000 200 100 10 20
	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());
	// 1 2 3 10000 10000 1000 200 100 10 20
	printDeque(d1);
}
void test03()
{
	deque<int>d1;
	d1.push_back(10);
	d1.push_back(20);
	d1.push_front(100);
	d1.push_front(200);
	printDeque(d1);

	//删除
	deque<int>::iterator it = d1.begin(); 
	it++;
	d1.erase(it);
	// 200 10 20
	printDeque (d1) ;
	
	//按区间方式删除
	//d1.erase(d1.begin(),d1.end()); 
	//清空
	d1.clear();
	printDeque(d1);
}
int main() 
{
	//test01();
	//test02();
	test03();
	system("pause");
	return 0;
}

总结:

插入和删除提供的位置是迭代器!

  • 尾插— push_back
  • 尾删— pop_back
  • 头插— push_front
  • 头删— pop_front

3.3.6 deque数据存取

功能描述:

对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);

	//通过[]方式访问元素
	// 300 200 100 10 20 30
	for (int i = 0; i < d1.size(); i++) 
	{
		cout << d1[i] << " ";
	}
	cout << endl;
	通过at方式
	for (int i = 0; i < d1.size(); i++)
	{
		cout << d1.at(i) << " ";
	}
	cout << endl;

	cout << "第一个元素为: "<< d1.front() << endl; 
	cout << "最后一个元素: " << d1.back() << endl;
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

3.3.7 deque排序

功能描述:

  • 利用算法实现对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;
}
//deque容器排序
void test01()
{
	deque<int>d;
	d.push_back(10); 
	d.push_back(20);
	d.push_back(30);
	d.push_front(100); 
	d.push_front(200); 
	d.push_front(300);
	
	//300 200 100 10 20 30
	printDeque(d);
	
	//排序  升序
	//对于支持随机访问的迭代器的容器,都可以利用sort算法直接对其进行排序
	//vector容器也可以利用sort进行排序
	sort(d.begin(),d.end()); 
	cout << "排序后:" << endl; 
	printDeque(d);
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

总结: sort算法非常实用,使用时包含头文件algorithm即可

3.5 stack容器

3.5.1 stack基本概念

概念: stack是一种先进后出(First In Last Out,FILO)的数据结构,它只有一个出口

image-20220424165938019

栈中只有顶端的元素才可以被外界使用,因此栈不允许有遍历行为

先进后出

栈可以判断容器是否为空吗? 可以 empty

栈可以返回元素个数吗? 可以 size

3.5.2 stack常用接口

功能描述:栈容器常用的对外接口

构造函数︰

  • 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

3.6 queue容器

3.6.1 queue基本概念

**概念:**Queue是一种先进先出(First In First Out,FIFO)的数据结构,它有两个出口

image-20220424193519843

队列容器允许从一端新增元素,从另—端移除元素

队列中只有队头和队尾才可以被外界使用,因此队列不允许有遍历行为

队列中进数据称为—入队push

队列中出数据称为—出队pop

3.6.2 queue常用接口

功能描述:栈容器常用的对外接口

构造函数:

  • queue<T> que; //queue采用模板类实现,queue对象的默认构造形式
  • queue(const queue &que); //拷贝构造函数

赋值操作:

  • queue& operator=(const queue &que); //重载等号操作符

数据存取:

  • push(elem); //往队尾添加元素
  • pop(); //从队头移除第一个元素
  • back(); //返回最后一个元素
  • front(); //返回第一个元素

总结:

  • 入队— push
  • 出队— pop
  • 返回队头元素— front
  • 返回队尾元素— back
  • 判断队是否为空— empty
  • 返回队列大小— size

3.7 list容器

3.7.1 list基本概念

功能:将数据进行链式存储

链表(list)是一种物理存储单元上非连续的存储结构,数据元素的逻辑顺序是通过链表中的指针链接实现的

链表的组成:链表由一系列结点组成

结点的组成:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域

STL中的链表是一个双向循环链表

**优点:**可以对任意位置进行快速插入或删除元素

**缺点:**容器遍历速度,没有数组快

占用空间比数组大

image-20220424201826930image-20220424202121126

image-20220424202150752

由于链表的存储方式并不是连续的内存空间,因此链表list中的迭代器只支持前移和后移,属于双向迭代器

list的优点:

  • 采用动态存储分配,不会造成内存浪费和溢出
  • 链表执行插入和删除操作十分方便,修改指针即可,不需要移动大量元素

list的缺点:

  • 链表灵活,但是空间(指针域)和时间(遍历)额外耗费较大

List有一个重要的性质,插入操作和删除操作都不会造成原有list迭代器的失效,这在vector是不成立的

总结:STL中List和vector是两个最常被使用的容器,各有优缺点

3.7.2 list构造函数

功能描述:

  • 创建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;
}
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常用容器,熟练掌握即可

3.7.3 list赋值和交换

功能描述:

  • 给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; // operator=赋值
	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;
}

3.7.4 list大小操作

功能描述:

  • 对list容器的大小进行操作

函数原型:

  • size() ; //返回容器中元素的个数
    empty( ); //判断容器是否为空
    resize(num ) ; //重新指定容器的长度为num,若容器变长,则以默认值填充新位置。//如果容器变短,则末尾超出容器长度的元素被删除。
    resize(num,elem); //重新指定容器的长度为num,若容器变长,则以elem值填充新位置。//如果容器变短,则末尾超出容器长度的元素被删除。
  • 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);
	if (L1.empty()) 
	{
		cout << "L1为空"<<endl;
	}
	else
	{
		cout << "L1不为空"<< endl;
		cout << "L1的大小为:" << L1.size() << endl;
	}
	//重新指定大小L1.resize(10);printList(L1);
	L1.resize(2); 
	printList(L1);
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

3.7.5 list插入和删除

功能描述:

  • 对list容器进行数据的插入和删除

函数原型:

  • push_back(elem);//在容器尾部加入一个元素
  • pop_back();//删除容器中最后一个元素.
  • push_front(elem);//在容器开头插入一个元素
  • pop_front();/l从容器开头移除第一个元素
  • insert(pos,elem);//在pos位置插elem元素的拷贝,返回新数据的位置。
  • insert(pos,n,elem);//在pos位置插入n个elem数据,无返回值。
  • insert(pos,beg,end);//在pos位置插入[beg,end)区间的数据,无返回值。
  • clear();//移除容器的所有数据
  • erase(beg,end);//删除[beg,end)区间的数据,返回下一个数据的位置。
  • erase(pos);//删除pos位置的数据,返回下一个数据的位置。
  • remove(elem);//删除容器中所有与elem值匹配的元素。
#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<int>L;
	//尾插
	L.push_back(10); 
	L.push_back(20); 
	L.push_back(30); 
	//头插
	L.push_front(100); 
	L.push_front(200); 
	L.push_front(300);
	printList(L);

	//尾删
	L.pop_back(); 
	printList(L);
	//头删
	L.pop_front(); 
	printList(L);
	//插入
	list<int>::iterator it = L.begin(); 
	L.insert(++it,1000);
	printList(L);

	//删除
	it = L.begin(); L.erase(++it); printList(L);
	
	//移除
	L.push_back(10000); 
	L.push_back(10000); 
	L.push_back(10000); 
	printList(L);
	L.remove(10000); 
	printList(L);
	
	//清空
	L.clear(); 
	printList(L);
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

3.7.6 list 数据存取

功能描述:

对list容器中数据进行存取

函数原型;

  • front(); //返回第一个元素。
  • back(); //返回最后一个元素。
#include<iostream>
using namespace std;
#include<list>

//list容器   数据存取
void test01()
{
	list<int>L;
	L.push_back(10);
	L.push_back(20);
	L.push_back(30);
	L.push_back(30);

	//L1[0]不可以用[访问list容器中的元素
	//L1.at(O)不可以用at方式访问list容器中的元素
	//原因是list本质链表,不是用连续线性空间存储数据,迭代器也是不支持随机访问的

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

	//验证迭代器是不支持随机访问的
	list<int>::iterator it = L.begin(); 
	it++; // 支持双向
	it--;
	//it = it + 1;//不支持随机访问
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

3.7.7 list反转和排序

功能描述:

  • 将容器中的元素反转,以及将容器中的数据进行排序

函数原型:

  • reverse(); //反转链表
  • sort(); //链表排序
#include<iostream>
using namespace std;
#include<list>
#include<algorithm>

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<int>L;
	L.push_back(20);
	L.push_back(10);
	L.push_back(50);
	L.push_back(40);
	L.push_back(30);

	cout << "反转前:" << endl; 
	printList(L);
	
	//反转
	L.reverse(); 
	cout << "反转后:" << endl;
	printList(L);
}
bool myCompare(int v1, int v2)
{
	//降序  就让第一个数 〉第二个数
	return v1 > v2;
}
void test02()
{
	list<int>L;
	L.push_back(20);
	L.push_back(10);
	L.push_back(50);
	L.push_back(40);
	L.push_back(30);

	//所有不支持随机访问迭代器的容器,不可以用标准算法
	//不支持随机访问迭代器的容器,内部会提供对应一些算法
	// sort(L1.begin(),L1.end ());
	L.sort();//升序
	printList(L);
	L.sort(myCompare);//降序
	printList(L);
}
int main() 
{
	//test01();
	test02();
	system("pause");
	return 0;
}

3.8 set/multiset容器

3.8.1 set基本概念

简介:

  • 所有元素都会在插入时自动被排序

本质:

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

set和multiset区别:

  • set不允许容器中有重复的元素
  • multiset允许容器中有重复的元素

3.8.2 set构造和赋值

功能描述:创建set容器以及赋值

构造:

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

赋值:

  • set& operator=( const set &st); //重载等号操作符

    #include<iostream>
    using namespace std;
    #include<set>
    
    void printSet(const set<int>&s)
    {
    	for (set<int>::const_iterator it = s.begin(); it != s.end(); it++)
    	{
    		cout << *it << " ";
    	}
    	cout << endl;
    }
    void test01()
    {
    	set<int>s1;
    
    	s1.insert(10);
    	s1.insert(40);
    	s1.insert(30);
    	s1.insert(20);
    	s1.insert(30);
    	
    	//遍历容器
    	// set容器特点:所有元素插入时候自动被排序
    	//set容器不允许插入重复值
    	printSet(s1);
    	
    	//拷贝构造
    	set<int>s2(s1); 
    	printSet(s2);
    }
    int main() 
    {
    	test01();
    	system("pause");
    	return 0;
    }
    

    3.8.3 set大小和交换

    功能描述:

    • 统计set容器大小以及交换set容器

    函数原型:

    • size(); //返回容器中元素的数目
    • empty); //判断容器是否为空
    • swap(st); //交换两个集合容器
#include<iostream>
using namespace std;
#include<set>

void printSet(const set<int>&s)
{
	for (set<int>::const_iterator it = s.begin(); it != s.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void test01()
{
	set<int>s1;

	s1.insert(10);
	s1.insert(30);
	s1.insert(20);
	s1.insert(40);
	
	printSet(s1);
	if (s1.empty())
	{
		cout << "s1为空" << endl;
	}
	else
	{
		cout << "s1不为空" << endl;
		cout << "s1的大小为:" << s1.size() << endl;
	}
}
void test02()
{
	set<int>s1;
	s1.insert(10);
	s1.insert(30);
	s1.insert(20);
	s1.insert(40);

	set<int>s2;
	s2.insert(100);
	s2.insert(300);
	s2.insert(200);
	s2.insert(400);

	printSet(s1);
	printSet(s2);

	s1.swap(s2);
	printSet(s1);
	printSet(s2);
}
int main() 
{
	//test01();
	test02();
	system("pause");
	return 0;
}

3.8.4 set插入和删除

功能描述:

  • set容器进行插入数据和删除数据

函数原型:

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

void printSet(const set<int>&s)
{
	for (set<int>::const_iterator it = s.begin(); it != s.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void test01()
{
	set<int> s1;
	
	//插入
	s1.insert(10); 
	s1.insert(30); 
	s1.insert(20); 
	s1.insert(40); 
	printSet(s1);
	
	//删除
	s1.erase(s1.begin()); 
	printSet(s1);
	s1.erase(30); 
	printSet(s1);
	
	//清空
	//s1.erase(s1.begin(), s1.end()); 
	s1.clear();
	printSet(s1);
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

3.8.5 set查找和统计

功能描述:

  • 对set容器进行查找数据以及统计数据

函数原型:

  • find(key) ; //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();
  • count(key); //统计key的元素个数
#include<iostream>
using namespace std;
#include<set>

void printSet(const set<int>&s)
{
	for (set<int>::const_iterator it = s.begin(); it != s.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void test01()
{
	set<int> s1;
	
	s1.insert(10); 
	s1.insert(30); 
	s1.insert(20); 
	s1.insert(40); 
	printSet(s1);
	
	set<int>::iterator pos = s1.find(30); 
	if (pos != s1.end())
	{
		cout << "找到元素:" << *pos << endl;
	}
	else 
	{
		cout << "未找到元素"<< endl;
	}
}
void test02()
{
	set<int> s1;

	s1.insert(10);
	s1.insert(30);
	s1.insert(20);
	s1.insert(40);
	s1.insert(30);
	printSet(s1);

	//统计30的个数
	int num = s1.count(30);
	//对于set而言统计结果要么是0要么是1
	cout << "num = " << num << endl;
}
int main() 
{
	//test01();
	test02();
	system("pause");
	return 0;
}

3.8.6 set和multiset区别

学习目标:

  • 掌握set和multiset的区别

区别:

  • set不可以插入重复数据,而multiset可以
  • set插入数据的同时会返回插入结果,表示插入是否成功
  • multiset不会检测数据,因此可以插入重复数据
#include<iostream>
using namespace std;
#include<set>

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;
}

3.8.7 pair对组创建

功能描述:

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

两种创建方式:

  • pair<type, type> p (value1,value2 );
  • pair<type, type> p = make_pair(value1,value2);
#include<iostream>
using namespace std;
#include<string>

void test01()
{
	//第一种方式
	pair<string,int>p("Tom",20);
	cout << "姓名:" << p.first << "年龄:"<< p.second << endl;
	
	//第二种方式
	pair<string,int>p2 = make_pair("Jerry",30);
	cout << "姓名:" << p2.first << "年龄:"<< p2.second << endl;
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

3.8.8 set容器排序

学习目标:

  • set容器默认排序规则为从小到大,掌握如何改变排序规则

主要技术点:

  • 利用仿函数,可以改变排序规则
#include<iostream>
using namespace std;
#include<set>

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;
}
#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对象
	Person p1("刘备",24);
	Person p2("关羽",28);
	Person p3("张飞",25);
	Person p4("赵云",21);
	
	s.insert(p1);
	s.insert(p2); 
	s.insert(p3); 
	s.insert(p4);
	
	for (set<Person>::iterator it = s.begin(); it != s.end(); it++)
	{
		cout << "姓名:" << it->m_Name << "年龄:" << it->m_Age << endl;
	}
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

3.9 map/multimap容器

3.9.1 map基本概念

简介:

  • map中所有元素都是pair
  • pair中第一个元素为key(键值),起到索引作用,第二个元素为value(实值)
  • 所有元素都会根据元素的键值自动排序

本质:

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

优点:

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

map和multimap区别:

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

3.9.2 map构造和赋值

功能描述:

  • 对map容器进行构造和赋值操作

函数原型:

构造:

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

赋值:

  • map& operator=(const map &mp); //重载等号操作符
#include<iostream>
using namespace std;
#include<map>
#include<string>

//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> m;

	m.insert(pair<int,int>(1,10)); 
	m.insert(pair<int,int>(3,30)); 
	m.insert(pair<int,int>(2,20)); 
	m.insert(pair<int,int>(4,40));

	printMap(m);

	//拷贝构造
	map<int, int>m2(m); 
	printMap(m2);
	
	//赋值
	map<int,int>m3; 
	m3 = m2;
	printMap(m3);
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

3.9.3 map大小和交换

功能描述:

统计map容器大小以及交换map容器

函数原型:

  • size(); //返回容器中元素的数目
  • empty(); //判断容器是否为空
  • swap(st); //交换两个集合容器
#include<iostream>
using namespace std;
#include<map>
#include<string>

//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));

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

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

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

	cout << "交换前"<<endl;
	printMap(m);
	printMap(m2);
	
	cout << "交换后" <<endl;
	m.swap(m2);
	printMap(m); 
	printMap(m2);
}
int main() 
{
	//test01();
	test02();
	system("pause");
	return 0;
}

3.9.4 map插入和删除

功能描述:

  • map容器进行插入数据和删除数据

函数原型:

  • insert(elem); //在容器中插入元素。
  • clear(); //清除所有元素
  • erase(pos); //删除pos迭代器所指的元素,返回下一个元素的迭代器。
  • erase(beg,end); //删除区间[beg,end)的所有元素,返回下一个元素的迭代器。
  • erase(key); //删除容器中值为key的元素。
#include<iostream>
using namespace std;
#include<map>
#include<string>

//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(make_pair(2,20)); 
	//第三种插入方式
	m.insert(map<int,int>::value_type(3,30));
	//第四种插入方式
	m[4] = 40;
	printMap(m);
	
	//删除
	m.erase(m.begin()); 
	printMap(m);
	m.erase(3); 
	printMap(m);

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

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

3.9.5 map查找和统计

功能描述:

  • 对map容器进行查找数据以及统计数据

函数原型:

  • find(key); //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();
  • count(key); //统计key的元素个数
#include<iostream>
using namespace std;
#include<map>

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

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

总结:

  • 查找— find(返回的是迭代器)
  • 统计— count(对于map,结果为0或者1)

3.9.6 map容器排序

学习目标:

  • 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(make_pair(1,10)); 
	m.insert(make_pair(2,20)); 
	m.insert(make_pair(3,30)); 
	m.insert(make_pair(4,40)); 
	m.insert(make_pair(5,50));
	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容器

4.STL-函数对象

4.1函数对象

4.1.1函数对象概念

概念:

  • 重载函数调用操作符的类,其对象常称为函数对象
  • 函数对象使用重载的()时,行为类似函数调用,也叫仿函数

本质:

函数对象(仿函数)是一个类,不是一个函数

4.1.2函数对象使用

特点:

  • 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值

  • 函数对象超出普通函数的概念,函数对象可以有自己的状态

  • 函数对象可以作为参数传递

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

//1.函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
class MyAdd
{
public:
	int operator () (int v1, int v2) 
	{
		return v1 + v2;
	}
};
void test01()
{
	MyAdd myAdd;
	cout << myAdd(10, 10) << endl;
}
//2、函数对象超出普通函数的概念,函数对象可以有自己的状态
class MyPrint
{
public:
	MyPrint() 
	{
		this->count = 0;
	}
	void operator() (string test)
	{
		cout << test << endl;
		this->count++;
	}
	int count;//自己内部的状态
};
void test02()
{
	MyPrint myPrint;
	myPrint("hello world"); 
	myPrint("hello world"); 
	myPrint("hello wor1d"); 
	myPrint("hello world");
	cout << "myPrint调用次数为:" << myPrint.count << endl;
}
//3、函数对象可以作为参数传递
void doPrint(MyPrint & mp, string test)
{
	mp(test);
}
void test03()
{
	MyPrint myPrint;
	doPrint(myPrint,"Hello c++");
}
int main() 
{
	//test01();
	//test02();
	test03();
	system("pause");
	return 0;
}

4.2谓词

4.2.1谓词概念

概念:

  • 返回bool类型的仿函数称为谓词
  • 如果operator()接受一个参数,那么叫做一元谓词
  • 如果operator()接受两个参数,那么叫做二元谓词

4.2.2一元谓词

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

// 1.—元谓词
struct GreaterFive {
	bool operator()(int val) {
		return val > 5;
	}
};

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

	vector<int>::iterator it = find_if(v.begin(),v.end(),GreaterFive()); 
	if (it == v.end()) 
	{
		cout << "没找到!"<< endl;
	}
	else 
	{
		cout << "找到:" << *it << endl;
	}
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

4.2.3 二元谓词

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

// 1.二元谓词
class MyCompare 
{
public:
	bool operator()(int num1,int num2) 
	{
		return num1 > num2;
	}
};
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;
	cout << "-----------------" << endl;

	//使用函数对象改变算法策略,排序从大到小
	sort(v.begin(), v.end(), MyCompare());
	for (vector<int> ::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
int main() 
{
	test01();
	system("pause");
	return 0;
}

4.3内建函数对象

4.3.1内建函数对象意义

概念:

  • STL内建了一些函数对象

分类:

  • 算术仿函数
  • 关系仿函数
  • 逻辑仿函数

用法:

  • 这些仿函数所产生的对象,用法和一般函数完全相同
  • 使用内建函数对象,需要引入头文件#include<functional>

4.3.2算术仿函数

功能描述:

  • 实现四则运算
  • 其中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>

void test01()
{
	negate<int>n;
	cout << n(50) << endl;
}
// plus
void test02()
{
	plus<int> p;
	cout << p(10,20) << endl;
}
int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}

4.3.3关系仿函数

功能描述:

  • 实现关系对比

仿函数原型:

  • 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<algorithm>
#include<vector>
#include<functional>

class MyCompare {
public:
	bool operator()(int v1, int v2) {
		return v1 >v2;
	}
};
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);
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 
	{
		cout << *it << " ";
	}
	cout << endl;

	// 自己实现仿函数
	//sort(v.begin(), v.end(), MyCompare()); 
	// STL内建仿函数大于仿函数
	sort(v.begin(), v.end(), greater<int>());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 
	{
		cout << *it << " ";
	}
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

4.3.4逻辑仿函数

功能描述:

  • 实现逻辑运算

函数原型:

  • 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<algorithm>
#include<vector>
#include<functional>

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;
}

5.STL-常用算法

概述:

  • 算法主要是由头文件组成。
  • 是所有STL头文件中最大的一个,范围涉及到比较、交换、查找、遍历操作、复制、修改等等
  • 体积很小,只包括几个在序列上面进行简单数学运算的模板函数
  • 定义了一些模板类,用以声明函数对象。

5.1常用遍历算法

学习目标:

  • 掌握常用的遍历算法

算法简介:

  • for_each //遍历容器
  • transform //搬运容器到另一个容器中

5.1.1 for_each

功能描述:

  • 实现遍历容器

函数原型:

  • for_each(iterator beg,iterator ene,_func);

    //遍历算法遍历容器元素
    //beg 开始迭代器
    //end结束迭代器
    //_func函数或者函数对象

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

void myprint01(int val1)
{
	cout << val1 << ' ';
}
class myprint02
{
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(), myprint01);
	cout << endl;

	for_each(v.begin(), v.end(), myprint02());
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结: for_each在实际开发中是最常用遍历算法,需要熟练掌握

5.1.2 transform

功能描述:

  • 搬运容器到另一个容器中

函数原型:

  • transform(iterator beg1, iterator endt1, iterator beg2,_func);

//beg1源容器开始迭代器

//end1源容器结束迭代器

//beg2目标容器开始迭代器

//_func函数或者函数对象

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

class Trans
{
public:
	int operator()(int v)
	{
		return v+100;
	}
};
class myprint
{
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>vTarget;
	vTarget.resize(v.size());

	transform(v.begin(), v.end(), vTarget.begin(), Trans());
	for_each(vTarget.begin(), vTarget.end(), myprint());
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结:搬运的目标容器必须要提前开辟空间,否则无法正常搬运

5.2常用查找算法

学习目标:

  • 掌握常用的查找算法

算法简介:

  • find //查找元素
  • find_if //按条件查找元素
  • adjacent_find //查找相邻重复元素
  • binary_search //二分查找法
  • count //统计元素个数
  • count_if //按条件统计元素个数

5.2.1 find

功能描述:

  • 查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end()

函数原型:

  • find(iterator beg, iterator end,value) ;

//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置

//beg开始迭代器

//end结束迭代器

//value查找的元素

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

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

	vector<int>::iterator it = find(v.begin(), v.end(), 5);
	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;
	}
	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);

	vector<Person>::iterator it = find(v.begin(), v.end(), p2);
	if (it == v.end())
	{
		cout << "没有找到!" << endl;
	}
	else
	{
		cout << "找到姓名;" << it->m_name << "年龄: " << it->m_age << endl;
	}
}
int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}

5.2.2 find_if

功能描述:

  • 按条件查找元素

函数原型:

  • find_if(iterator beg, iterator end,_Pred);

//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置_

//beg 开始迭代器

//end结束迭代器

//_Pred函数或者谓词(返回bool类型的仿函数)

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

//内置数据类型
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+1);
	}
	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;
	}
	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);

	vector<Person>::iterator it = find_if(v.begin(),v.end(),Greater20()); 
	if (it == v.end())
	{
		cout << "没有找到!" << endl;
	}
	else
	{
		cout << "找到姓名:" << it->m_name << "年龄:"<< it->m_age << endl;
	}
}
int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}

5.2.3 adjacent_find

功能描述:

  • 查找相邻重复元素

函数原型:

  • adjacent_find( iterator beg, iterator end ) ;

查找相邻重复元素,返回相邻元素的第一个位置的迭代器

//beg 开始迭代器
//end结束迭代器

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

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 pos = adjacent_find(v.begin(), v.end());

	if (pos == v.end() ){
		cout << "未找到相邻重复元素"<< endl ;
	}
	else {
		cout << "找到相邻重复元素:" << *pos << endl;
	}
}
int main()
{
	test01();
	system("pause");
	return 0;
}

5.2.4 binary_search

功能描述:

  • 查找指定元素是否存在

函数原型:

  • bool binary_search(iterator beg, iterator end, value);

//查找指定的元素,查到返回true否则false

//注意:在无序序列中不可用

//beg 开始迭代器

//end结束迭代器

//value查找的元素

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

void test01()
{
	vector<int>v;
	
	for (int i = 0; i < 10; i++) 
	{
		v.push_back(i);
	}
	//二分查找
	bool ret = binary_search(v.begin(), v.end(), 2); 
	if (ret)
	{
		cout << "找到了" <<endl;
	}
	else {
		cout << "未找到" << endl;
	}
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结:二分查找法查找效率很高,值得注意的是查找的容器中元素必须是有序序列

5.2.5 count

功能描述:

  • 统计元素个数

函数原型:

  • count(iterator beg, iterator end,value) ; //统计元素出现次数

//beg开始迭代器 //end结束迭代器 //value统计的元素

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

void test01()
{
	vector<int> v; 
	
	v.push_back(1); 
	v.push_back(2); 
	v.push_back(4); 
	v.push_back(5); 
	v.push_back(3); 
	v.push_back(4); 
	v.push_back(4);
	
	int num = count(v.begin(), v.end(), 4);
	
	cout << "4的个数为:" << 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("刘备",35); 
	Person p2("关羽",35);
	Person p3("张飞",35); 
	Person p4("赵云",30); 
	Person p5("曹操",25);
	
	v.push_back(p1);
	v.push_back(p2); 
	v.push_back(p3); 
	v.push_back(p4); 
	v.push_back(p5);
	
	Person p("诸葛亮",35);
	
	int num = count(v.begin(), v.end(), p); 
	cout << "num = " << num << endl;
}
int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}

总结:统计自定义数据类型时候,需要配合重载operator==

5.2.6 count_if

功能描述:

  • 按条件统计元素个数

函数原型:

  • count_if(iterator beg, iterator end,_Pred ) ;

//按条件统计元素出现次数

//beg开始迭代器 //end结束迭代器 //_Pred谓词

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

//统计内置数据类型
class Greater20
{
public:
	bool operator() (int val) 
	{
		return val > 20;
	}
};
void test01()
{
	vector<int> v; 
	
	v.push_back(10); 
	v.push_back(40); 
	v.push_back(30); 
	v.push_back(20); 
	v.push_back(40); 
	v.push_back(20); 
	
	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;
	}
	bool operator == (const Person &p)
	{
		if (this->m_age == p.m_age)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	string m_name;
	int m_age;
};
class AgeGreater20
{
public:
	bool operator() (const Person & p) {
		return p.m_age > 20;
	}
};
void test02()
{
	vector<Person> v;
	Person p1("刘备", 35);
	Person p2("关羽", 35);
	Person p3("张飞", 35);
	Person p4("赵云", 30);
	Person p5("曹操", 25);

	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);
	v.push_back(p5);

	int num = count_if(v.begin(), v.end(), AgeGreater20());
	cout << "num = " << num << endl;
}
int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}

5.3常用排序算法

学习目标:

  • 掌握常用的排序算法

算法简介:

  • sort //对容器内元素进行排序
  • random_shuffle //洗牌指定范围内的元素随机调整次序
  • merge //容器元素合并,并存储到另一容器中
  • reverse //反转指定范围的元素

5.3.1 sort

功能描述:

  • 对容器内元素进行排序

函数原型:

  • sort(iterator beg,iterator end,_Pred ) ;

//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置

//beg开始迭代器 //end结束迭代器 // _Pred 谓词

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

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(20); 
	v.push_back(40);
	
	//sort默认从小到大排序
	sort(v.begin(), v.end());
	
	for_each(v.begin(), v.end(), myPrint); 
	cout << endl;
	
	//从大到小排序
	sort(v.begin(), v.end(), greater<int>());
	for_each(v.begin(), v.end(), myPrint); 
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结: sort属于开发中最常用的算法之一,需熟练掌握

5.3.2 random_shuffle

功能描述:

  • 洗牌指定范围内的元素随机调整次序

函数原型:

  • random_shuffle(iterator beg, iterator end ) ;

//指定范围内的元素随机调整次序

//beg 开始迭代器 //end结束迭代器

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

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;
}

总结:random_shuffle洗牌算法比较实用,使用时记得加随机数种子

5.3.3 merge

功能描述:

  • 两个容器元素合并,并存储到另一容器中

函数原型:

  • 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<algorithm>
#include<vector>

class myPrint
{
public:
	void operator() (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;
}

总结:merge合并的两个容器必须的有序序列

5.3.4 reverse

功能描述:

  • 将容器内元素进行反转

函数原型:

  • reverse(iterator beg, iterator end) ;

//反转指定范围的元素

//beg开始迭代器 //end结束迭代器

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

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v; 
	v.push_back(10); 
	v.push_back(30); 
	v.push_back(50); 
	v.push_back(20); 
	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;
}

总结:reverse反转区间内元素,面试题可能湖及到

5.4常用拷贝和替换算法

学习目标:

  • 掌握常用的拷贝和替换算法

算法简介:

  • copy //容器内指定范围的元素拷贝到另—容器中
  • replace //将容器内指定范围的旧元素修改为新元素
  • replace_if //容器内指定范围满足条件的元素替换为新元素
  • swap //互换两个容器的元素

5.4.1 copy

功能描述:

  • 容器内指定范围的元素拷贝到另一容器中

函数原型:

  • copy(iterator beg, iterator end, iterator dest);

//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置

//beg开始迭代器 //end 结束迭代器 //dest目标起始迭代器

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

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v1;

	for (int i = 0; i < 10; i++) 
	{
		v1.push_back(i + 1);
	}
	vector<int> v2;
	v2.resize(v1.size());
	
	copy(v1.begin(),v1.end(),v2.begin());
	
	for_each(v2.begin(), v2.end(),myPrint()); 
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

注:提前开辟空间

5.4.2 replace

功能描述:

  • 将容器内指定范围的旧元素修改为新元素

函数原型:

  • replace(iterator beg, iterator end,oldvalue,newvalue);

//将区间内旧元素替换成新元素

//beg开始迭代器 //end结束迭代器

//oldvalue 旧元素 //newvalue 新元素

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

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v;

	v.push_back(20); 
	v.push_back(30); 
	v.push_back(20); 
	v.push_back(40); 
	v.push_back(50); 
	v.push_back(10);
	v.push_back(20);
	
	cout << "替换前:"<<endl;
	for_each(v.begin(), v.end(), myPrint()); 
	cout << endl;
	
	//将容器中的20替换成2000
	cout<<"替换后:" << endl;
	replace(v.begin(), v.end(),20, 2000); 
	for_each(v.begin(), v.end(), myPrint()); 
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结: replace会替换区间内满足条件的元素

5.4.3 replace_if

功能描述:

  • 将区间内满足条件的元素,替换成指定元素

函数原型:

  • replace_if(iterator beg,iterator end,_pred,newvalue);

//按条件替换元素,满足条件的替换成指定元素

//beg开始迭代器 //end结束迭代器

//_pred谓词 //newvalue替换的新元素

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

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
class ReplaceGreater30 {
public:
	bool operator()(int val) {
		return val >= 30;
	}
};
void test01()
{
	vector<int> v;

	v.push_back(20); 
	v.push_back(30); 
	v.push_back(20); 
	v.push_back(40); 
	v.push_back(50); 
	v.push_back(10);
	v.push_back(20);
	
	cout << "替换前:"<<endl;
	for_each(v.begin(), v.end(), myPrint()); 
	cout << endl;
	
	//将容器中大于等于的38替换成3000
	cout <<"替换后: "<< endl;
	replace_if(v.begin(), v.end(), ReplaceGreater30(),3000);
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结: replace_if按条件查找,可以利用仿函数灵活筛选满足的条件

5.4.4 swap

功能描述:

  • 互换两个容器的元素

函数原型:

  • swap( container c1, container c2);

//互换两个容器的元素

//c1容器1 //c2容器2

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

class myPrint
{
public:
	void operator() (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;
}

总结: swap交换容器时,注意交换的容器要同种类型

5.5常用算术生成算法

学习目标:

  • 掌握常用的算术生成算法

注意:

  • 算术生成算法属于小型算法,使用时包含的头文件为#include

算法简介:

  • accumulate //计算容器元素累计总和
  • fill //向容器中添加元素

5.5.1 accumulate

功能描述:

  • 计算区间内容器元素累计总和
#include<iostream>
using namespace std;
#include<numeric>
#include<vector>

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v; 
	for (int i = 0; i <= 100; i++) {
		v.push_back(i);
	}
	
	//参数3  起始累加值
	int total = accumulate(v.begin(), v.end(), 0);

	cout << total << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结: accumulate使用时头文件注意是numeric,这个算法很实用

5.5.2 fill

功能描述:

  • 向容器中填充指定的元素

函数原型:

  • fill(iterator beg, iterator end,value) ;//向容器中填充元素

//beg 开始迭代器 //end结束迭代器 //value填充的值

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

class myPrint
{
public:
	void operator() (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可以将容器区间内元素填充指定的值

5.6常用集合算法

学习目标:

  • 掌握常用的集合算法

算法简介:

  • set_intersection //求两个容器的交集
  • set_union //求两个容器的并集
  • set_difference //求两个容器的差集

5.6.1 set_intersection

功能描述:

  • 求两个容器的交集

函数原型:

  • set_intersection(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<numeric>
#include<vector>
#include<algorithm>

class myPrint
{
public:
	void operator() (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;
	// 取两个里面较小的值给目标容器开辟空间
	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返回值既是交集中最后一个元素的位置

5.6.2 set_union

功能描述:

  • 求两个集合的并集

函数原型:

  • set_union(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>

class myPrint
{
public:
	void operator() (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;
	// 给目标容器开辟空间
	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返回值既是并集中最后一个元素的位置

5.6.3 set_difference

功能描述:

  • 求两个集合的差集

函数原型:

  • set_difference(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>

class myPrint
{
public:
	void operator() (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;
	// 给目标容器开辟空间
	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;

	itEnd = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), vTarget.begin());
	for_each(vTarget.begin(), itEnd, myPrint());
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结:

  • 求差集的两个集合必须的有序序列
  • 目标容器开辟空间需要从两个容器取较大值
    iterator end) ;`

//反转指定范围的元素

//beg开始迭代器 //end结束迭代器

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

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v; 
	v.push_back(10); 
	v.push_back(30); 
	v.push_back(50); 
	v.push_back(20); 
	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;
}

总结:reverse反转区间内元素,面试题可能湖及到

5.4常用拷贝和替换算法

学习目标:

  • 掌握常用的拷贝和替换算法

算法简介:

  • copy //容器内指定范围的元素拷贝到另—容器中
  • replace //将容器内指定范围的旧元素修改为新元素
  • replace_if //容器内指定范围满足条件的元素替换为新元素
  • swap //互换两个容器的元素

5.4.1 copy

功能描述:

  • 容器内指定范围的元素拷贝到另一容器中

函数原型:

  • copy(iterator beg, iterator end, iterator dest);

//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置

//beg开始迭代器 //end 结束迭代器 //dest目标起始迭代器

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

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v1;

	for (int i = 0; i < 10; i++) 
	{
		v1.push_back(i + 1);
	}
	vector<int> v2;
	v2.resize(v1.size());
	
	copy(v1.begin(),v1.end(),v2.begin());
	
	for_each(v2.begin(), v2.end(),myPrint()); 
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

注:提前开辟空间

5.4.2 replace

功能描述:

  • 将容器内指定范围的旧元素修改为新元素

函数原型:

  • replace(iterator beg, iterator end,oldvalue,newvalue);

//将区间内旧元素替换成新元素

//beg开始迭代器 //end结束迭代器

//oldvalue 旧元素 //newvalue 新元素

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

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v;

	v.push_back(20); 
	v.push_back(30); 
	v.push_back(20); 
	v.push_back(40); 
	v.push_back(50); 
	v.push_back(10);
	v.push_back(20);
	
	cout << "替换前:"<<endl;
	for_each(v.begin(), v.end(), myPrint()); 
	cout << endl;
	
	//将容器中的20替换成2000
	cout<<"替换后:" << endl;
	replace(v.begin(), v.end(),20, 2000); 
	for_each(v.begin(), v.end(), myPrint()); 
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结: replace会替换区间内满足条件的元素

5.4.3 replace_if

功能描述:

  • 将区间内满足条件的元素,替换成指定元素

函数原型:

  • replace_if(iterator beg,iterator end,_pred,newvalue);

//按条件替换元素,满足条件的替换成指定元素

//beg开始迭代器 //end结束迭代器

//_pred谓词 //newvalue替换的新元素

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

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
class ReplaceGreater30 {
public:
	bool operator()(int val) {
		return val >= 30;
	}
};
void test01()
{
	vector<int> v;

	v.push_back(20); 
	v.push_back(30); 
	v.push_back(20); 
	v.push_back(40); 
	v.push_back(50); 
	v.push_back(10);
	v.push_back(20);
	
	cout << "替换前:"<<endl;
	for_each(v.begin(), v.end(), myPrint()); 
	cout << endl;
	
	//将容器中大于等于的38替换成3000
	cout <<"替换后: "<< endl;
	replace_if(v.begin(), v.end(), ReplaceGreater30(),3000);
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结: replace_if按条件查找,可以利用仿函数灵活筛选满足的条件

5.4.4 swap

功能描述:

  • 互换两个容器的元素

函数原型:

  • swap( container c1, container c2);

//互换两个容器的元素

//c1容器1 //c2容器2

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

class myPrint
{
public:
	void operator() (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;
}

总结: swap交换容器时,注意交换的容器要同种类型

5.5常用算术生成算法

学习目标:

  • 掌握常用的算术生成算法

注意:

  • 算术生成算法属于小型算法,使用时包含的头文件为#include

算法简介:

  • accumulate //计算容器元素累计总和
  • fill //向容器中添加元素

5.5.1 accumulate

功能描述:

  • 计算区间内容器元素累计总和
#include<iostream>
using namespace std;
#include<numeric>
#include<vector>

class myPrint
{
public:
	void operator() (int val) {
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v; 
	for (int i = 0; i <= 100; i++) {
		v.push_back(i);
	}
	
	//参数3  起始累加值
	int total = accumulate(v.begin(), v.end(), 0);

	cout << total << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结: accumulate使用时头文件注意是numeric,这个算法很实用

5.5.2 fill

功能描述:

  • 向容器中填充指定的元素

函数原型:

  • fill(iterator beg, iterator end,value) ;//向容器中填充元素

//beg 开始迭代器 //end结束迭代器 //value填充的值

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

class myPrint
{
public:
	void operator() (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可以将容器区间内元素填充指定的值

5.6常用集合算法

学习目标:

  • 掌握常用的集合算法

算法简介:

  • set_intersection //求两个容器的交集
  • set_union //求两个容器的并集
  • set_difference //求两个容器的差集

5.6.1 set_intersection

功能描述:

  • 求两个容器的交集

函数原型:

  • set_intersection(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<numeric>
#include<vector>
#include<algorithm>

class myPrint
{
public:
	void operator() (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;
	// 取两个里面较小的值给目标容器开辟空间
	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返回值既是交集中最后一个元素的位置

5.6.2 set_union

功能描述:

  • 求两个集合的并集

函数原型:

  • set_union(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>

class myPrint
{
public:
	void operator() (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;
	// 给目标容器开辟空间
	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返回值既是并集中最后一个元素的位置

5.6.3 set_difference

功能描述:

  • 求两个集合的差集

函数原型:

  • set_difference(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>

class myPrint
{
public:
	void operator() (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;
	// 给目标容器开辟空间
	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;

	itEnd = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), vTarget.begin());
	for_each(vTarget.begin(), itEnd, myPrint());
	cout << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结:

  • 求差集的两个集合必须的有序序列
  • 目标容器开辟空间需要从两个容器取较大值
  • set_difference返回值既是差集中最后一个元素的位置
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值