自己学习c++过程中写下的笔记,只做基础了解使用
01书写helloworld
#include <iostream>
using namespace std;int main() {cout << "Hello World" << endl;system("pause");return 0;}
02变量创建的方法
#include <iostream>
using namespace std;int main() {//变量创建的方法int a = 10;cout << "a = " << a << endl;system("pause");return 0;}
03常量的定义方式
#include <iostream>
using namespace std;/*常量的定义方式1. #define 宏常量注意,定义宏常量,后面不要加分号;2. const修饰的变量不可修改,也称之为常量const修饰的变量一般在主方法中const 比 define更好1. const方式可以明确指定类型2. 可以使用c++的作用域规则,将定义限制在特定的函数或文件中(作用域规则描述了名称在各个模块中的可知程度)3. const可以用在更复杂的场景
*/
//1.
#define Day 7int main() {cout << "一周总共有" << Day << "天" << endl;//2. const int mouth = 12;cout << "一年有" << mouth << "个月" << endl;system("pause");return 0;}
04 关键字
#include<iostream>
using namespace std;
/**/
int main() {//创建变量int a = 10;//这里的int就是关键字,不要用关键字给变量或常量起名称return 0;
}
05 标识符命名规则
#include<iostream>
using namespace std;
/*c++规定给标识符(变量,常量)命名时候,有一套自己的规则1. 标识符不可以是关键字2. 标识符只可以由字母,数字,下划线组成3. 第一个字符必须是字母或下划线4. 标识符的字母区分大小写
*/
int main() {return 0;
}
06 数据类型 整型
#include<iostream>
using namespace std;
/*1. 首先说明数据类型存在的意义,也就是为什么要区分数据类型:给变量分配合适的内存空间,避免空间浪费2. 整型变量表示的是整数类型的数据c++中可以表示整型的类型有以下几种方式,区别在于所占内存空间的不同1. short,2字节,-2^15~2^15-12. int,4字节3. long,windows为4字节,linux为4(32位操作系统)/8(64位操作系统)字节4. long long,8字节3. c++中,除非有理由存储为其他类型(例如用了特殊后缀表示特定的类型,或者值太大,不可以存储为int),否则c++将整型常量存储为int类型4. 常见的后缀l/L longu/U unsigned intul unsigned longull5. 长度1. 对于十进制来说,对于不带后缀的十进制整数,将依次使用int ,long, long long来表示,例如20000就用int,而40000就用long2. 对于八进制和十六进制,而是依次使用int,unsigned int,unsigned long,unsigned long long ,这是因为十六进制通常用来表示内存地址,而内存地址是没有负数的*/
int main() {short num1 = 32769;int num2 = 10;long num3 = 10;long long num4 = 10;cout << "num1 = " << num1 << endl;//-32767,因为超过了short的数据范围cout << "num2 = " << num2 << endl;cout << "num3 = " << num3 << endl;cout << "num4 = " << num4 << endl;return 0;
}
07 sizeof
#include<iostream>
using namespace std;
/*利用sizeof关键字,可以统计数据类型所占内存的大小语法 : sizeof(数据类型/变量)
*/
int main() {int a = 10;cout << "short所占内存空间为 : " << sizeof(short) << endl; // 2cout << "int所占内存空间为 : " << sizeof(int) << endl; // 4cout << "long所占内存空间为 : " << sizeof(long) << endl; // 4cout << "long long 所占内存空间为 : " << sizeof(long long) << endl; // 8cout << "变量a所占内存空间为 : " << sizeof(a) << endl; // 4return 0;
}
08 浮点型
#include<iostream>
using namespace std;
/*作用 : 由于表示小数浮点型变量分为两种:1. 单精度 float2. 双精度 double两者的区别在于表示的有效数字范围不同flaot,4字节,有效数字范围7位double,8字节,有效数字范围15~16位注意: 默认情况下,输出小数会显示6为有效数字,无论是double还是float举例:3.14的有效数字为3位,31.4的有效数字也是3位浮点数的运算速度要比整数运算慢,且精度将降低
*/
int main() {float f1 = 3.1415926f; /*一般来说,我们会在单精度数字后面写一个 f ,如果没有 f ,编译器会把他当作一个双精度数字,因为编译器默认把小数视作双精度*/ //float f2 = 3.14;//cout << "f2没有在数字后面写f,那么他的占用内存空间为 : " << sizeof(f2) << endl; // 8double d1 = 3.1415926;//cout << "d2占用内存空间为 : " << sizeof(d1) << endl; // 8cout << f1 << endl;//3.14159cout << d1 << endl;//3.14159/*不管单精度还是双精度,如果表示一个小数,都只会最多表示6为有效数字,如果想显示更多有效数字,需要进行一些额外的配置这个过程比较复杂,后期学习*/return 0;
}
09 科学计数法
#include<iostream>
using namespace std;
/**/
int main() {float f1 = 3e2;float f2 = 3e-2;/*3e2如果e后面是一个正数,则代表3 * 10^23e-2如果e后面是一个负数,则代表3 * 10^-2*/cout << "f1 = " << f1 << endl; // 300cout << "f2 = " << f2 << endl; // 0.03return 0;
}
10 字符型
#include<iostream>
using namespace std;
/*字符型作用 : 字符型用于显示 单个 字符语法 : char ch = 'a';注意:1. 在显示字符型变量的时候,用单引号将字符括起来,不要用双引号2. 单引号内只能有一个字符,不可以是字符串1. c++中字符串变量只占用一个字节2. 字符型变量并不是把字符本身放到内存中存储,而是将对应的 ASC2 编码放入到存储单元中重点 : 在c++中,char其实也属于整型变量,所以可以对char类型数据进行整数操作,而且char中存放的,一定是对应的字符编码,只不过输出的时候,cout会根据值的类型选择如何显示值
*/
int main() {char ch = 'a';char ch2 = 65;cout << ch << endl; // acout << sizeof(ch) << endl; // 1cout << int(ch) << endl; // 97cout << "ch2 : " << ch2 << endl; //Achar c;cout << "请输入:";cin >> c;//5cout << c << " : " << (int)c; // 5 : 53cout << '\007';return 0;
}
11 转义字符
#include<iostream>
using namespace std;
/*\n : 换行\t : 水平制表,也就是一个TAB\\ : 代表一个反斜杠\\r : 回车\" : "\? : ?
*/
int main() {//想输出一个反斜杠//错误写法//cout << "\" << endl;// 正确写法cout << "\\" << endl;return 0;
}
12 *字符串型
#include<iostream>
#include<string> // 用c++风格字符串的时候,要包含这个头文件,vs2019可以不写
using namespace std;
/*字符串型作用 : 表示一串字符两种风格1. c语言风格: char 变量名[] = "字符串值";c语言风格字符串有一个特点,就是以空字符结尾 ,空字符被写作\0,其ASC2码值为0,用来标记字符串的结尾char str1[] = {'h','e','l','l','o','\0'};这样子写起来非常的复杂,所以我们可以使用引号括起来即可,并且这种方式不要我们添加空字符,它会隐式的包含char str1[] = "hello";2. c++语言风格: string 变量名 = "字符串值";string位于命名空间std中,string定义隐藏了字符串的 数组 性质注意 : 字符串常量和字符常量不可以互换例如:字符串常量 "S";他实际保存的是两个字符,'S'和'\0',并且"S"实际上表达的是字符串所在的地址而字符常量's,实际上保存的是ASC2,我们之前也说过,char数据类型其实属于整型
*/
int main() {//1. char str1[] = "我是何佳乐";//这种字符串被称之为字符串常量cout << str1 << endl;cout << sizeof(str1) << endl;//2. string str2 = "我也是何佳乐";cout << str2 << endl;cout << sizeof(str2) << endl;return 0;
}
13 *字符串案例
#include<iostream>
#include<cstring> // for the strlen function
using namespace std;
/*字符串案例通过该案例可以知道1. strlen返回的是存储在数组中的字符串长度,而不是数组本身的长度,并且strlen只计算可见的字符,不计算\02. cout输出字符串的时候,在扫描到\0的时候结束
*/
int main() {const int Size = 15;char name1[Size];char name2[Size] = "C++owboy";//初始化数组string name3 = "java is the \0 best";cout << "name2 = " << name2 << endl;cout << "what your name ?(name1)" << endl;cin >> name1;//basicnamecout << "strlen(name1) = " << strlen(name1) << endl;//9cout << "sizeof(name1) = " << sizeof(name1) << endl;//15cout << "name1[0] = " << name1[0] << endl;//b//可以通过设置\0来提前结束字符串的输出name2[3] = '\0';//这样子cout只会输出三个字符cout << "name2 = " << name2 << endl;//C++cout << name3;//java is thereturn 0;
}
14 字符串输入的陷阱
#include<iostream>
using namespace std;
/*字符串输入的陷阱
*/
int main() {/*string city,reason;cout << "请输入你最喜欢的城市" << endl;cin >> city;cout << "为什么最喜欢这里?" << endl;cin >> reason;cout << "city = " << city << endl;cout << "reason = " << reason << endl;*//*输出:请输入你最喜欢的城市new yark为什么最喜欢这里?city = newreason = yark*//*分析:我们可以发现,我们第二次cin什么都没有输入,结果就已经运行完成了,这是因为:cin使用空格,制表符和换行符来确定字符串的位置,这意味着用cin依次获取的是一个单词(new),获取该单词后,cin将new放入city,并自动在结尾添加空字符,这样子导致的结果就是,第一次cin将new放入city,而将york留在了输入队列当cin从输入队列中搜索输入数据的时候,发现了york,然后将york存入reason*//*解决方法:通过cin.getline()一次获取一行的输入,getline通过换行符确认输入结束*/cout << "----------------------------" << endl;const int arrSize = 20;char city2[arrSize];char reason2[arrSize];cout << "请输入你最喜欢的城市" << endl;cin.getline(city2,20); cout << "为什么最喜欢这里?" << endl;cin.getline(reason2, 20);cout << "city = " << city2 << endl;cout << "reason = " << reason2 << endl;/*输出:请输入你最喜欢的城市new york为什么最喜欢这里?fuck youcity = new yorkreason = fuck you*/return 0;
}
15 字符串赋值和拼接
#include<iostream>
using namespace std;
/**/
int main() {//1. 赋值char char1[20];char char2[20] = "jaguar";string str1;string str2 = "panther";;//用数组实现的字符串,也继承了数组的特点,比如不可以将数组赋值给另一个数组,下面的操作就是错误的//char1 = char2;//但是string可以,因为string其实是对象str1 = str2; cout << "str1 = " << str1 << endl;//2. 拼接str1 += "何佳乐";cout << "str1 = " << str1 << endl;cout << "str1 length is : " << str1.size();return 0;
}
16 *string和常规数字字符串
#include<iostream>
#include<string> // for getline function
using namespace std;
/*在获取长度,和从输入流获取数据的时候,c风格字符串和c++string字符串方式不一样
*/
int main() {char char1[20];string str;cout << "before length of char1 : " << strlen(char1) << endl;//31/*至于上面的输出为什么不是20,是因为strlen获得长度的方式是直到扫描到\0,但是我们初始化的数组并没有\0,所以strlen会继续向后扫描,直到在别的地方扫描到了\0*/cout << "before length of str: " << str.size() << endl;//0cout << "please enter for char1 : "; //new yorkcin.getline(char1, 20);//cin是iostream的对象,而getline是cin类的类方法,第一个参数是目标数组,第二个参数是数组长度//getline使用他来避免超越数组的边界cout << "please enter for str : ";//zhan sangetline(cin, str);//这里要注意,与c风格字符串获取输入的方式不一样/*这里的getline不是类方法,因为iostream其实是c就有的库,那个时候没有string数据类型,所以没有对应string的getline方法至于为什么istream没有处理string的类方法,为什么还可以执行cin >> str,这涉及到友元函数,之后讲*/cout << "after length of char1 : " << strlen(char1) << endl; // 8cout << "after length of str : " << str.size() << endl; // 8return 0;
}
17 原始字符串
#include<iostream>
using namespace std;
/*原始字符串原始字符串以"( 和 )"作为开始和结束,并且用R标识
*/
int main() {cout << R"(jim "kind" tutt uses "\n" instead of endl. )" << endl;//如果需要在原始字符串中输入"(的话,我们可以修改原始字符串的定界符cout << R"+++("我是何佳乐,我活得很快乐哦\n")+++" << endl;/*上面的代码中, 我们用"+++( 和 +++)" 代替了原始的定界符但是注意,相比较原始的定界符,我们只可以在" 和 ( 之间添加元素来扩充定界符,扩充后,cout扫描到)"就不会认为字符串输入结束,所以原始字符串可以正确输入)"*//*jim "kind" tutt uses "\n" instead of endl."我是何佳乐,我活得很快乐哦\n"*/return 0;
}
18 布尔类型 bool
#include<iostream>
using namespace std;
/*布尔类型 boolbool只有两个值1. true -- 真(本质是1),只要是非0值都代表true2. false -- 假(本质是0)bool类型占1个字节大小
*/
int main() {bool b1 = false;cout << b1 << endl;cout << "bool占用的内存空间为 : "<< sizeof(bool) << endl; // 1return 0;
}
19 数据的输入
#include<iostream>
#include<string>
using namespace std;
/*数据的输入作用 : 用于从键盘获取数据关键字 : cin >> 变量*/
int main() {//整型输入//int a = 0;//cout << "请输入整型变量" << endl;//cin >> a;//cout << "a = " << a << endl;//浮点型输入//double d = 0;//cout << "请输入浮点型变量" << endl;//cin >> d;//cout << "d = " << d << endl;/*字符型输入char ch = 'a';cout << "请输入字符型变量" << endl;cin >> ch;cout << "ch = " << ch << endl;*///字符串输入/*string str = "hello";cout << "请输入字符串变量" << endl;cin >> str;cout << "str = " << str << endl;*///布尔类型输入bool b = true;cout << "请输入布尔数据类型变量" << endl;cin >> b;cout << b << endl;
}
20 比较运算符
#include<iostream>
using namespace std;
/**/
int main() {int num1 = 10;int num2 = 13;cout << (num1 > num2) << endl;cout << (num1 == num2) << endl;cout << (num1 < num2) << endl;return 0;
}
21 赋值运算符
#include<iostream>
using namespace std;
/**/
int main() {int a = 10;a = 100;cout << "a = " << a << endl;//100a += a;cout << "a = " << a << endl;//200a *= a;cout << "a = " << a << endl;//40000a %= a;cout << "a = " << a << endl;//0return 0;
}
22 逻辑运算符
#include<iostream>
using namespace std;
/*逻辑运算符:! && ||
*/
int main() {cout << !true << endl;//0cout << (true && false) << endl;//0cout << (true || false) << endl;//1return 0;
}
23 算术运算符
#include<iostream>
using namespace std;
/*运算符作用 : 用于执行代码的运算1. 算数运算符,四则运算+ - * / %(取余,取模) ++ -- (分前置和后置)注意 : 1. 除0会报错integer division by zero2. 只有整数可以取模,小数不可以取模2. 赋值运算符3. 比较运算符,返回布尔类型数据4. 逻辑运算符,返回布尔类型数据
*/
int main() {// 算数运算符:/int num1 = 10;int num2 = 3;double d1 = 10;double d2 = 3;cout << num1 / num2 << endl;//整数相除-->会舍弃所有小数位,只保留整数部分cout << d1 / d2 << endl;//3.33333,浮点型数值相除,或者两个数中有一个是浮点数-->保留小数,结果是浮点数//注意://cout << 10 / 0 << endl;//这里会报错,要极度注意 -->除0异常<-- cout << 10 % 3 << endl;//10/3余数为1,所以这里输出的是1//cout << 10.0 % 3.0 << endl;//编译期间报错,因为只有整数可以取模,小数不可以取模//递增运算符cout << num1++ << endl;//10cout << num1 << endl;//11cout << ++num2 << endl;//4cout << num2 << endl;//4cout << 11.17 + 50.25 << endl;return 0;
}
24 选择结构
#include<iostream>
using namespace std;
/*选择结构1. 单行格式if语句2. 多行格式if语句3. 多条件的if语句
*/
int main() {//输入一个分数,如果分数大于600分,视为考上一本大学,并在屏幕上打印int score = 0;cout << "请输入学生的成绩" << endl;cin >> score;if (score > 600){if (score >700){cout << "您考上了清华大学" << endl;}else if (score > 650) {cout << "您考上了中国科学技术大学" << endl;}else {cout << "您考上了复旦大学" << endl;}}else if (score >500){cout << "您考上了二本大学" << endl;}else if (score > 400) {cout << "您考上了三本大学" << endl;}else {cout << "大专" << endl;}return 0;
}
25 案例 : 求三个数的最大值
#include<iostream>
using namespace std;
/*利用选择结构,从三个值中找出最大值
*/
int main() {int num1 = 3120;int num2 = 212310;int num3 = 310;if (num1 > num2){if (num1 > num3){cout << "最大值为 : " << num1 << endl;}else {cout << "最大值为 : " << num3 << endl;}}else {if (num2 > num3){cout << "最大值为 : " << num2 << endl;}else {cout << "最大值为 : " << num3 << endl;}}return 0;
}
26 三目运算符
#include<iostream>
using namespace std;
/*三目运算符
*/
int main() {int num1 = 10;int num2 = 20;int c = num1 > num2 ? num1 : num2;cout << c << endl;//20num1 > num2 ? num1 : num2 = 100;cout << "num1 : " << num1 << endl;//10cout << "num2 : " << num2 << endl;//100return 0;
}
27 switch
#include<iostream>
using namespace std;
/*switch 语句作用 : 执行多条件分支语句注意:> 注意1:switch语句中表达式类型只能是整型或者字符型> 注意2:case里如果没有break,那么程序会一直向下执行> 总结:与if语句比,对于多条件判断时,switch的结构清晰,执行效率高,缺点是switch不可以判断区间
*/
int main() {//请给电影评分 //10 ~ 9 经典 // 8 ~ 7 非常好// 6 ~ 5 一般// 5分以下 烂片int score = 0;cout << "请输入你对该电影的评分 : " << endl;cin >> score;switch (score){case 10:case 9 : cout << "经典" << endl;break;case 8:case 7:cout << "非常好" << endl;break;case 6:case 5:cout << "一般" << endl;break;default:cout << "烂片" << endl;break;}return 0;
}
28 while循环结构
#include<iostream>
#include<ctime>
using namespace std;
/*系统随机生成一个1到100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果猜对恭喜玩家胜利并且退出游戏。
*/
int main() {//添加一个随机数的种子,利用当前系统时间生成随机数,防止每次随机数都是42(伪随机数)srand((unsigned int)time(NULL));int num1 = rand() % 100 + 1;//rand % 100 生成0 ~ 99的随机数,然后+1 就是 1~100int num2 = 0;while (1){cout << "请输入你猜测的值" << endl;cin >> num2;if (num1 > num2){cout << "猜小了" << endl;}else if (num1 < num2){cout << "猜大了" << endl;}else{cout << "恭喜你猜对了" << endl;break;}}return 0;
}
29 do-while循环结构
#include<iostream>
using namespace std;
/*do-while循环语句作用 : 满足循环条件,执行循环语句语法 : do{循环语句} while (循环条件);注意 : 与while循环语句的差别在于do-while循环会先执行一遍循环语句,然后再进行判断
*/
int main() {int num = 0;do{cout << num << endl;num++;} while (num < 10);// 0 1 2 3 4 5 6 7 8 9return 0;
}
30 案例 : 水仙花数
#include<iostream>
using namespace std;
/*练习案例:水仙花数案例描述:水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身例如:1^3 + 5^3+ 3^3 = 153请利用do...while语句,求出所有3位数中的水仙花数
*/
int main() {int num = 100;do{int num1 = num / 100; // 获取百位int num2 = num / 10 % 10; // 获取十位int num3 = num % 10; // 获取个位if (num == (num1*num1*num1 + num2*num2*num2 + num3*num3*num3)){cout << num << endl;}num++;} while (num < 1000);return 0;
}
31 for循环
#include<iostream>
using namespace std;
/*for循环练习案例:敲桌子案例描述:从1开始数到数字100, 如果数字个位含有7,或者数字十位含有7,或者该数字是7的倍数,我们打印敲桌子其余数字直接打印输出。
*/
int main() {for (int i = 1; i <= 100 ; i++){ //数字各位为7||数字是7的倍数||数字的十位有7if (i % 10==7 || i % 7 == 0 || i / 10 == 7){cout << "敲桌子" << endl;}else {cout << i << endl;}}return 0;
}
32 案例 : 循环嵌套实现九九乘法表
#include<iostream>
using namespace std;
/*九九乘法表
*/
int main() {for (int i = 1; i < 10; i++){for (int j = 1; j <= i; j++){cout << j << " * " << i << " = " << i * j << "\t";}cout << endl;}return 0;
}
33 break
#include<iostream>
using namespace std;
/*break语句作用 : 用于跳出选择结构或循环结构break的使用时机:1. 出现在switch语句中,作用是终止case并跳出switch2. 出现在循环语句中,作用是跳出当前的循环语句3. 出现在内层循环中,作用是跳出最近的内层循环
*/
int main() {//比如说九九乘法表,不打印5for (int i = 1; i < 10; i++){for (int j = 1; j <= i; j++){if (i == 5){break;}cout << j << " * " << i << " = " << i * j << "\t";}cout << endl;}return 0;
}
34 continue
#include<iostream>
using namespace std;
/*continue语句作用 : 在循环语句中,跳过本次循环中余下尚未执行的语句,继续下一次循环*/
int main() {//打印1~100,但是跳过偶数for (int i = 1; i <= 100; i++){if (i % 2 == 0){continue;}cout << i << endl;}return 0;
}
35 goto
#include<iostream>
using namespace std;
/*作用:可以无条件跳转语句语法: goto 标记解释:如果标记的名称存在,执行到goto语句时,会跳转到标记的位置注意:在程序中不建议使用goto语句,以免造成程序流程混乱
*/
int main() {cout << "1" << endl;goto FLAG;cout << "2" << endl;cout << "3" << endl;cout << "4" << endl;FLAG:cout << "5" << endl;return 0;
}
36 *一维数组
#include<iostream>
using namespace std;
/*数组 : 所谓数组,就是一个集合,里面存放了相同类型的数据元素特点1. 数组中每个数据元素都是相同的数据类型2. 数组是由连续的内存位置组成的一维数组1. 定义方式1. 数据类型 数组名[ 数组长度 ]; 2. 数据类型 数组名[ 数组长度 ] = { 值1,值2 ...};3. 数据类型 数组名[ ] = { 值1,值2 ...};2. 一维数组名称的用途,数组名就是数组的首地址1. 可以统计整个数组在内存中的长度2. 可以获取数组在内存中的首地址注意 : 1. 只有定义的时候可以批量初始化数组,如果定义的时候没有初始化数组,那么就只可以根据数组下标初始化数组2. 不可以将数组赋值给另一个数组c++11新特性:1. 大括号初始化数组的时候可以不写等号2. 列表初始化不允许缩窄转换
*/
int main() {//定义方式1int score[10];//然后利用下标赋值score[0] = 1;score[1] = 2;score[2] = 3;score[3] = 4;//定义方式2int score2[10] = { 1,2,3,4,5,6,7 };//不够的补0/*for (int i = 0; i < 10; i++){cout << score2[i] << " " << endl;}*///定义方式3int score3[] = { 1,2,3,4,5 };//统计数组长度以及元素个数cout << "数组score3占用的内存空间为 : " << sizeof(score3) << endl;//20cout << "数组score3的每个元素占用的内存空间为 : " << sizeof(score3[0]) << endl;//4cout << "数组的元素个数为 : " << sizeof(score3) / sizeof(score3[0]) << endl;//5//获取数组在内存中的首地址,每次运行得到的地址都不一样cout << "数组首地址为(十进制) : " << (int)score3 << endl;cout << "数组首地址为(十六进制) : " << score3 << endl;cout << "数组中第一个元素地址为 : " << (int)&score[0] << endl;cout << "数组中第二个元素地址为 : " << (int)&score[1] << endl;//数组名是常量,不可以进行赋值操作//score3 = 100;//c++11新特性int score4[3]{ 1,2,3 };return 0;
}
37 案例 :五只小猪称体重
#include<iostream>
using namespace std;
/*练习案例:五只小猪称体重案例描述:在一个数组中记录了五只小猪的体重,如:int arr[5] = {300,350,200,400,250};找出并打印最重的小猪体重。*/
int main() {int arr[5] = { 300,350,200,400,250 };int max = arr[0];for (int i = 1; i < 5; i++){if (arr[i] > max){max = arr[i];}}cout << "最大值为 : " << max << endl;return 0;
}
38 案例 : 数组元素逆置
#include<iostream>
using namespace std;
/*练习案例:数组元素逆置案例描述:请声明一个5个元素的数组,并且将元素逆置.(如原数组元素为:1,3,2,5,4;逆置后输出结果为:4,5,2,3,1);
*/
int main() {int arr[] = { 1,3,2,5,4,1,2,5,3 };int temp = 0;//辅助变量,用于交换元素int length = sizeof(arr) / sizeof(arr[0]);for (int i = 0, j = length - 1; i <= length / 2; i++, j--){temp = arr[i];arr[i] = arr[j];arr[j] = temp;}for (int i = 0; i < length; i++){cout << arr[i] << " " << endl;}return 0;
}
39 冒泡排序
#include<iostream>
using namespace std;
/*实现冒泡排序
*/
int main() {int arr[] = {12,231,2315,42,12,6,213,76,2,87,57,4 };int length = sizeof(arr) / sizeof(arr[0]);//数组元素个数int temp = 0;//辅助变量,用于交换数据bool flag = false;for (int i = 0; i < length - 1; i++)//外层循环定义排序趟数{flag = false;for (int j = 1; j < length - i; j++){if (arr[j]>arr[j-1]){temp = arr[j];arr[j] = arr[j - 1];arr[j - 1] = temp;flag = true;}}if (!flag)//说明一趟排序中没有发生交换,则不用再进行之后的排序,数组已经有序{break;}}for (int i = 0; i < length; i++){cout << arr[i] << " " ;}return 0;
}
40 *二维数组
#include<iostream>
using namespace std;
/*二维数组 : 二维数组就是在一维数组上,多加一个维度。1. 定义方式:1. 数据类型 数组名[ 行数 ][ 列数 ]; 2. 数据类型 数组名[ 行数 ][ 列数 ] = { {数据1,数据2 } ,{数据3,数据4 } };3. 数据类型 数组名[ 行数 ][ 列数 ] = { 数据1,数据2,数据3,数据4};4. 数据类型 数组名[ ][ 列数 ] = { 数据1,数据2,数据3,数据4};建议:以上4种定义方式,利用第二种更加直观,提高代码的可读性总结: 在定义二维数组时,如果初始化了数据,可以省略行数2. 数组名:总结1:二维数组名就是这个数组的首地址总结2:对二维数组名进行sizeof时,可以获取整个二维数组占用的内存空间大小
*/
int main() {//方式1int arr[2][3];arr[0][0] = 1;arr[0][1] = 2;arr[0][2] = 3;arr[1][0] = 4;arr[1][1] = 5;arr[1][2] = 6;//for (int i = 0; i < 2; i++)//{// for (int j = 0; j < 3; j++)// {// cout << arr[i][j] << "\t";// }// cout << endl;//}方式2//int arr2[2][3] = { {11,22,33},{44,55,66} };//for (int i = 0; i < 2; i++)//{// for (int j = 0; j < 3; j++)// {// cout << arr2[i][j] << "\t";// }// cout << endl;//}方式3//int arr3[2][3] = { 10,11,12,13,14,15 };//for (int i = 0; i < 2; i++)//{// for (int j = 0; j < 3; j++)// {// cout << arr3[i][j] << "\t";// }// cout << endl;//}方式4//int arr4[][3] = { 6,5,4,3,2,1 };//for (int i = 0; i < 2; i++)//{// for (int j = 0; j < 3; j++)// {// cout << arr4[i][j] << "\t";// }// cout << endl;//}//查看二维数组所占用的空间cout << "二维数组占用的空间为 : " << sizeof(arr) << endl;//24//二维数组一行大小cout << "二维数组一行的大小 : " << sizeof(arr[0]) << endl;//12//二维数组一个数据元素的大小cout << sizeof(arr[0][0]) << endl; //4 cout << "行数 : " << sizeof(arr) / sizeof(arr[0]) << endl;//2cout << "列数 : " << sizeof(arr[0]) / sizeof(arr[0][0]) << endl;//3//地址cout << "首地址" << (int)arr << endl;cout << "第一行首地址" << (int)&arr[0] << endl;cout << "第一个元素地址" << (int)&arr[0][0] << endl;return 0;
}
41 案例 : 考试成绩统计
#include<iostream>
using namespace std;
/*考试成绩统计:案例描述:有三名同学(张三,李四,王五),在一次考试中的成绩分别如下表,请分别输出三名同学的总成绩
*/
int main() {int scores[3][3] ={{100,100,100},{90,50,100},{60,70,80},};string names[3] = { "张三","李四","王五" };for (int i = 0; i < 3; i++){int sum = 0;for (int j = 0; j < 3; j++){sum += scores[i][j];}cout << names[i] << "同学的总成绩为 : " << sum << endl;}return 0;
}
42 *函数
#include<iostream>
using namespace std;
/*1. 函数 : 作用 : 将一段经常使用的代码封装起来,减少重复代码,一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能2. 函数的定义 : 1. 返回值类型2. 函数名3. 参数表列4. 函数体语句5. return表达式返回值类型 函数名 (参数列表){函数体语句return表达式}3. 注意 : c++中,不允许函数的嵌套定义,每个函数的定义都是独立的,所有函数的创建都是平等的*///示例:定义一个加法函数,实现两个数相加
int add(int num1, int num2) {//num1 num2称之为形参,因为定义函数的时候,num1和num2并没有真实数据//当调用函数的时候,实参的值会传递给形参return num1 + num2;
}int main() {int a = 10;int b = 20;// a,b称之为实参int c = add(a, b);cout << "c = " << c << endl;return 0;
}
43 值传递
#include<iostream>
using namespace std;
/*值传递:所谓值传递,就是函数调用的时候,实参将数值传入给形参值传递的时候,如果形参发生任何改变,并不会影响实参
*///定义函数,实现两个数字进行交换
void swap(int num1, int num2) {//交换前cout << "交换前:num1 = " << num1 << endl;//10cout << "交换前:num2 = " << num2 << endl;//20int temp = num1;num1 = num2;num2 = temp;//交换后cout << "交换后:num1 = " << num1 << endl;//20cout << "交换后:num2 = " << num2 << endl;//10return;//没有返回值的时候,可以不写return
}int main() {int a = 10;int b = 20;swap(a, b);cout << "a = " << a << endl;//10cout << "b = " << b << endl;//20return 0;
}
44 函数声明
#include<iostream>
using namespace std;
/*函数声明作用 : 告诉编译器函数名称以及如何调用函数,函数的实际主体可以单独定义注意 : 函数的声明可以多次,但是函数的定义只可以有一次*/
//这里,函数的声明进行了四次
int max(int a, int b);
int max(int a, int b);
int max(int a, int b);
int max(int a, int b);int main() {int num1 = 10;int num2 = 20;cout << max(num1, num2) << endl;return 0;
}//函数的定义
int max(int a, int b) {return a > b ? a : b;
}
45 函数的分文件编写
- swap.h头文件
#pragma once
#include<iostream>
using namespace std;
//函数的声明
void swap(int a, int b);
- swap.cpp源文件
#include "swap.h"
//函数的定义
void swap(int a, int b) {int temp = a;a = b;b = temp;cout << "a = " << a << endl;cout << "b = " << b << endl;
}
#include "swap.h"
/*函数的分文件编写作用 : 让代码结构更加清晰步骤 :1. 创建后缀名为.h的头文件2. 创建后缀名为.cpp的源文件3. 在头文件中写函数的声明4. 在源文件中写函数的定义
*/
int main() {int a = 10;int b = 20;swap(a, b);return 0;
}
46 *指针的定义和使用
#include<iostream>
using namespace std;
/*指针 : 保存地址作用 : 可以通过指针间接访问内存(可以通过指针保存一个地址)注意 : 1. 内存编号是从0开始记录的,一般用十六进制数字表示 2. 可以利用指针变量保存地址& : 取地址符*p : 解引用
*/
int main() {//1. 定义一个指针int a = 10;//指针定义的语法 数据类型 * 指针变量名;int* p;//让指针记录变量a的地址p = &a;cout << "a的地址为" << &a << '\n'; cout << "指针p为" << p << '\n';//两者的输出是一样的//2. 如何使用指针//可以通过解引用 (指针前加*,找到指针指向的内存的数据) 的方式,找到指针指向的内存的数据cout << *p << '\n';return 0;
}
47 指针的占用空间
#include<iostream>
using namespace std;
/*指针所占的内存空间问 : 指针也是种数据类型,那么这种数据类型占用的空间是多少呢?答 : 所有指针类型,在32位操作系统(x86)下是4个字节,在64位(x64)下占8个字节
*/
int main() {int a = 10;long long b = 20;int* p;long long* p2 = &b;p = &a;//指针p指向a的地址cout << sizeof(p) << '\n';//4cout << sizeof(*p) << '\n';//4cout << sizeof(*p2) << '\n';//8cout << sizeof(char*) << '\n';//4cout << sizeof(float*) << '\n';//4cout << sizeof(double*) << '\n';//4cout << sizeof(bool*) << '\n';//4return 0;
}
48 空指针和野指针
#include<iostream>
using namespace std;
/*空指针 : 指针变量指向内存中编号为0的空间1. 用途 : 初始化指针变量 ( 创建了一个指针还不知道指哪,就可以让他先指NULL )2. 注意 : 空指针指向的内存是不可以访问的 野指针 : 指针变量指向非法的内存空间( 0~255之间的内存编号是系统占用的,因此不可以访问 )在程序中,一定要避免出现野指针总结 : 空指针和野指针都不是我们申请的空间,因此不要访问
*/
int main() {// 空指针int* p = NULL;cout << p << endl;//00000000//一旦执行 *p 就会报错// 野指针int* p2 = (int *)0x1100;//cout << *p2 << endl;//会报错 : 引发了异常: 读取访问权限冲突。return 0;
}
49 *conts修饰指针
#include<iostream>
using namespace std;
/*const修饰指针有三种情况:1. const修饰指针 -- 常量指针2. const修饰常量 -- 指针常量3. const即修饰指针,又修饰常量记忆方法 : 其实就看const是在 “*” 前面还是后面就得了。在 “*” 前面,就是指常量,在“*”后面就是指常指针。
*/
int main() {int a = 10;int b = 10;//const 修饰的是指针,指针的指向可以改,指针指向的值不可以改 --常量指针const int* p1 = &a;//const 修饰的是常量,指针的指向不可以改,指针指向的值可以更改 --指针常量int* const p2 = &b;//const 即修饰常量,也修饰指针const int* const p3 = &a;return 0;
}
50 指针和数组配合使用
#include<iostream>
using namespace std;
/*指针和数组作用 : 利用指针访问数组元素,数组名就是一个地址,是首地址
*/
int main() {int arr[] = { 1,2,3,4,5,6,7,8,9,10 };int* p = arr; // 指向数组的指针for (int i = 0; i < 10; i++){cout << *p << endl;p++;}return 0;
}
51 指针和函数
#include<iostream>
using namespace std;
/*指针和函数作用 : 利用指针作为函数参数,可以修改实参的值总结 : 如果不想修改实参,就用值传递,如果想修改实参,就用地址传递
*///值传递
void swap(int a, int b) {int temp = a;a = b;b = temp;
}//地址传递
void swap2(int* p1, int* p2) {//因为传入的是地址,所以需要用指针来接收int temp = *p1;*p1 = *p2;*p2 = temp;
}int main() {int a = 10;int b = 20;swap(a, b);cout << "值传递" << endl;cout << "a = " << a << endl;cout << "b = " << b << endl;swap2(&a, &b);//传入的是地址cout << "地址传递" << endl;cout << "a = " << a << endl;cout << "b = " << b << endl;return 0;
}
52 案例 : 指针 数组 函数
#include<iostream>
using namespace std;
/*案例描述 : 封装一个函数,利用冒泡排序,实现对整型数组的升序排序例如数组:int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };总结:当数组名传入到函数作为参数时,被退化为指向首元素的指针*/
//函数声明
void bubbleSort(int* arr, int len);
void printArray(int* arr, int len);//主函数
int main() {int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };int len = sizeof(arr) / sizeof(arr[0]);bubbleSort(arr, len);printArray(arr, len);return 0;
}//函数的定义
void bubbleSort(int* arr, int len) {for (int i = 0; i < len - 1 ; i++){for (int j = 1; j < len - i; j++){if (arr[j] < arr[j - 1]){int temp = arr[j];arr[j] = arr[j - 1];arr[j - 1] = temp;}}}
}
void printArray(int* arr, int len) {for (int i = 0; i < len; i++){cout << arr[i] << endl;}
}
53 结构体
#include<iostream>
using namespace std;
/*结构体基本概念 : 结构体属于用户自定义的数据类型,允许用户存储不同的数据类型结构体的定义和使用1. 语法:struct 结构体名 { 结构体成员列表 };2. 通过结构体创建变量的方式有三种 :1. struct 结构体名 变量名2. struct 结构体名 变量名 = {成员1值,成员2值,成员3值...}1~2的struct关键字可以省略3. 定义结构体的时候顺便创建变量总结1:定义结构体时的关键字是struct,不可省略总结2:创建结构体变量时,关键字struct可以省略总结3:结构体变量利用操作符 ''.'' 访问成员
*///结构体的定义
struct student
{string name;//姓名int age = 0; //年龄int score = 0; //分数
}stu3;//方式3-->定义结构体的时候顺便创建变量int main() {//方式3stu3.name = "何佳乐";stu3.age = 22;stu3.score = 100;cout << stu3.name << " + " << stu3.age << " + " << stu3.score << endl;//方式1student stu1;stu1.name = "吴超";stu1.age = 21;stu1.score = 100;cout << stu1.name << " + " << stu1.age << " + " << stu1.score << endl;//方式2student stu2 = { "曹越" , 23 , 100 };cout << stu2.name << " + " << stu2.age << " + " << stu1.score << endl;return 0;
}
54 结构体数组
#include<iostream>
using namespace std;
/*结构体数组作用 : 将自定义的结构体放入到数组中方便维护语法 : struct 结构体名 数组名[ 元素个数 ] = { {},{},{}...};结构体指针作用 : 通过指针访问结构体中的成员总结 : 结构体指针可以通过 -> 操作符 来访问结构体中的成员
*/ //结构体的定义
struct student {string name;int age;int score;
};int main() {student stus[3] = {{"zhangsan" , 12 , 100},{"lisi" , 14 , 100},{"wangwu" , 19 , 100}};cout << sizeof(stus) / sizeof(stus[0]) << endl;//3for (int i = 0; i < 3; i++){cout << "姓名 : " << stus[i].name << "\t年龄 : " << stus[i].age << "\t成绩 : " << stus[i].score << endl;}//结构体指针student* p = stus;cout << "姓名 : " << p->name << "\t年龄 : " << p->age << "\t成绩 : " << p->score << endl;p++;cout << "姓名 : " << p->name << "\t年龄 : " << p->age << "\t成绩 : " << p->score << endl;p++;cout << "姓名 : " << p->name << "\t年龄 : " << p->age << "\t成绩 : " << p->score << endl;return 0;
}
55 结构体嵌套
#include<iostream>
using namespace std;
/*结构体嵌套结构体作用 : 结构体中的成员可以是另一个结构体例如 : 每个老师辅导一个学生,一个老师的结构体中,记录一个学生的结构体总结 : 在结构体中可以定义另一个结构体作为成员,用来解决实际问题
*///学生结构体定义
struct student {string name; //学生姓名int age; //学生年龄int score; //学生成绩
};
//老师结构体定义
struct teacher {int id; //老师的工号string name; //老师姓名int age; //老师年龄student stu; //老师辅导的学生
};int main() {student stu1 = { "zhangsan" , 12 , 100 };teacher tea1 = { 12 , "laoshi" , 44 , stu1 };cout << "老师工号 : " << tea1.id << "\t老师姓名 : " << tea1.name << "\t老师年龄 : " << tea1.age << "\t老师辅导的学生的成绩" << tea1.stu.score << endl;return 0;
}
56 *结构体做函数参数
#include<iostream>
using namespace std;
/*结构体做函数参数:说明 : 我在学习的过程中,因为是先学习的java,所以将地址传递联想到了java的引用类型,然后想当然的把struct类比为java中的类,那自然默认是引用类型传递,也就是当结构体做函数传递的时候,结构体变量名就是地址,其实这是错误的,c++中struct也属于普通的数据类型,也有值传递和地址传递总结 : 如果不想修改主函数中的数据,用值传递,反之用地址传递
*/struct student {string name;int age;int score;
};//值传递
void printStudent1(student stu) {stu.age = 40;cout << "姓名 : " << stu.name << "\t年龄 : " << stu.age << "\t成绩 : " << stu.score << endl;}//地址传递
void printStudent2(student* stu) {stu->age = 40;cout << "姓名 : " << stu->name << "\t年龄 : " << stu->age << "\t成绩 : " << stu->score << endl;}int main() {student stu = { "何佳乐" , 22 , 100 };cout << "值传递" << endl;printStudent1(stu);cout << "姓名 : " << stu.name << "\t年龄 : " << stu.age << "\t成绩 : " << stu.score << '\n' << endl;cout << "地址传递" << endl;printStudent2(&stu);cout << "姓名 : " << stu.name << "\t年龄 : " << stu.age << "\t成绩 : " << stu.score << endl;return 0;
}
57 结构体和const
#include<iostream>
using namespace std;
/*结构体中const的使用场景作用 : 用const来防止误操作
*/struct student {string name;int age;int score;
};//const的使用场景
void printStudent(const student* stu) {//不可操作,因为const在*前,所以stu是常量,我们无法修改常量的值,这个时候只可以修改指针的指向//stu->age = 100;//修改指向/*student stu2 = { "李四",18,100 };stu = &stu2;*/cout << "姓名 : " << stu->name << "\t年龄 : " << stu->age << "\t成绩 : " << stu->score << endl;
}int main() {student stu = { "张三",18,100 };printStudent(&stu);return 0;
}
58 结构体案例1
#include<iostream>
using namespace std;
/*案例描述 :学校正在做毕设项目,每名老师带领5个学生,总共有3名老师,需求如下设计学生和老师的结构体,其中在老师的结构体中,有老师姓名和一个存放5名学生的数组作为成员学生的成员有姓名、考试分数,创建数组存放3名老师,通过函数给每个老师及所带的学生赋值最终打印出老师数据以及老师所带的学生数据。*///定义结构体
struct student {string name;int score;
};
struct teacher {string name;student stus[5];
};
//定义函数
void allocateSpace(teacher tArray[], int len) {string tName = "教师";string sName = "学生";string nameSeed = "ABCDE";for (int i = 0; i < len; i++){tArray[i].name = tName + nameSeed[i];for (int j = 0; j < 5; j++){tArray[i].stus[j].name = sName + nameSeed[j];tArray[i].stus[j].score = rand() % 61 + 40;//0~60 + 1 --> 1~100}}
}
void printTeachers(teacher tArray[], int len) {for (int i = 0; i < len; i++){cout << tArray[i].name << endl;for (int j = 0; j < 5; j++){cout << "\t姓名 : " << tArray[i].stus[j].name << "\t分数 : " << tArray[i].stus[j].score << endl;}}
}int main() {srand((unsigned int)time(NULL));teacher tArray[3];int len = sizeof(tArray) / sizeof(tArray[0]);allocateSpace(tArray, len);printTeachers(tArray, len);return 0;
}
59 结构体案例2
#include<iostream>
using namespace std;
/*案例描述:设计一个英雄的结构体,包括成员姓名,年龄,性别;创建结构体数组,数组中存放5名英雄。通过冒泡排序的算法,将数组中的英雄按照年龄进行升序排序,最终打印排序后的结果。
*///定义英雄结构体
struct Hero {string name;int age;string sex;
};
//定义冒泡排序方法
void bubbleSort(Hero heros[], int len)
{bool flag = false;for (int i = 0; i < len - 1; i++) {for (int j = 1; j < len - i; j++){if (heros[j].age < heros[j - 1].age){/*int temp = heros[j].age;heros[j].age = heros[j - 1].age;heros[j - 1].age = temp;*/Hero temp = heros[j];heros[j] = heros[j - 1];heros[j - 1] = temp;flag = true;}}if (!flag){break;}flag = false;}
}
//打印数组
void printHeros(Hero heros[], int len)
{for (int i = 0; i < len; i++){cout << "姓名 : " << heros[i].name << "\t年龄 : " << heros[i].age << "\t性别 : " << heros[i].sex << endl;}
}
int main() {Hero heros[5] = {{"刘备",23,"男"},{"关羽",22,"男"},{"张飞",20,"男"},{"赵云",21,"男"},{"貂蝉",19,"女"}};bubbleSort(heros, 5);printHeros(heros, 5);return 0;
}
60 *namespace
#include<iostream>
//using namespace std;
//using std::cout;
//using std::endl;
/*namespace可以方便我们的操作,如果我们编写的是大型项目,或者将多个厂商现有的代码组合起来的时候,会有一个潜在的问题可能会有多个已封装好的产品存在相同的函数,这个时候编译器就无法确切的知道这个函数是属于哪个版本的了,命名空间可以让厂商将其产品封装在一个名称空间的单元中,这样子就可以使用名称空间的名称来具体指出想使用哪个厂商的产品所以,如果没有using namespace std;cout << "--" << endl;应该写成std::cout << "--" << std::endl;所以using namespace std;可以看作偷懒的行为,让我们可以少些很多内容,但是在实际开发中,我们推荐下面的写法using std::coutusing std::endl还需要注意的是,我们经常会将命名空间写在头文件名后面,但是这并不是强制的,我们也可以将命名空间写到main函数里面,那么这个时候,命名空间只针对main函数,比如在test方法中,cout << "曹越" << endl;语句就是错误的当前通行的理念是,只让需要访问命名空间std的函数访问他是最好的选择,比如有两个函数main和test,只有main需要用到cout,而tset不需要,那么这个时候我们最好将命名空间的定义放到main函数中,而不是放到函数外,使得只有mian函数可以访问命名空间*/
void test() {//会报错//cout << "曹越" << endl;
}
int main() {using std::cout;using std::endl;//std::cout << "何佳乐" << std::endl;cout << "何佳乐" << endl;return 0;
}
61 *cout和endl
#include<iostream>
using namespace std;
/*1. cout:1. cout 是一个预定义的对象,知道如何显示字符串,数字和单个字符(提前了解对象 : 对象是类的特定实例,而类定义了数据的存储和实现方式,这里表现了对象的长处,不了解对象的内部情况就可以使用他,只需要知道他的接口,即如何使用他)2. 整数25与字符串25存在天壤之别,计算机中,整数25存储的是25对应的二进制,而字符串25存储的是2和5分别对应的ASC2编码,这里我们就要夸一夸cout的聪明了,cout可以知道要输出的是字符串还是整数还是浮点数,而老式的printf不可以,他需要程序员指定要输出的是哪种数据类型cout的智能行为源自c++的面向对象特性,c++插入运算符(<<)将根据其后的数据类型相对应的调整其行为,这是一个运算符重载的例子,cout是可扩展的,我们可以重新定义<<运算符,使得cout可以识别和显示所开发的新数据类型2. endl:endl是一个特殊的c++符号,表示一个重要的概念,重启一行3. endl和'\n'(选自书上的一段话,个人没有完全理解)endl确保程序继续运行前刷新输出(将其立刻显示在屏幕上),而使用'\n'不能够提供这样子的保证,这意味着在有些系统中又是可能在您输入信息后才会出现提示*/
int main() {return 0;
}
62 *赋值语句
#include<iostream>
using namespace std;
/*赋值语句将值赋给存储单元,例如,下面的句子将整数25赋值给变量carrots标识的内存单元carrots = 25;c++和c不一样的地方在于,c++允许连续使用赋值运算符(=),例如,下面的语句在c++中是正确的num1 = num2 = num3 = 10;这里要注意的是,赋值是从右至左进行的,首先,10先赋值给num3,然后num3的值赋值给num2,最后num2的值赋值给num1
*/
int main() {return 0;
}
63 声明语句和变量
#include<iostream>
using namespace std;
/*计算机是一种精确的,有条理的机器,要将信息项存储到计算机中,就必须指出信息的存储位置和所需的内存空间在c++中,完成这一任务有一种相对简便的方法,就是使用声明语句来指出存储类型并提供位置标签例如 : int carrots;这条语句包含了两个信息,需要的内存以及该内存单元的名称1. 在c++中,int表示整数,这条语句指出程序需要足够的存储空间来存储一个整数2. 第二项任务是给存储单元指定名称,因为我们要是每次使用数据都要写出该数据的存储位置的话,会非常麻烦,因为数据的存储地址通常都是16进制的数字,所以我们给存储单元指定一个名字,跳过该名字使用数据,会方便程序员的操作.该声明语句指出,之后将使用carrots来标识存储在该内存单元中的值,carrots被称之为变量,因为他的值可以修改程序中的声明语句叫做定义声明语句,简称为定义,当然,之后还会学习到更为复杂的 引用声明
*/
int main() {int carrots;return 0;
}
64 unsigned
#include<iostream>
#include<climits>
#define ZERO 0;/*unsigned 代表无符号数在double ,int , long , long long前加上unsigned就会变为对应的无符号数,无符号数的好处是没有负值,所以可以扩大数字的表示范围,最好用在没有负数的情况,比如人口,资源总量等等注意 : unsigned 就是unsigned int 的缩写下面的例子可以明显的表示出unsigned的特点,并且要观察发生溢出后的结果有什么规律*/
int main() {using namespace std;short sam = SHRT_MAX; // 32767 最大值unsigned short sue = sam; // sue = sam = 32767,无符号数short的最大值为65535,表示范围为0~65535cout << "sam = " << sam << endl;//32767cout << "sue = " << sue << endl;//32767sam = sam + 1; sue = sue + 1;cout << "sam = " << sam << endl; //-32768cout << "sue = " << sue << endl; //32768-->因为无符号数的表示范围更大sam = ZERO;sue = ZERO;cout << "sam = " << sam << endl; // 0cout << "sue = " << sue << endl; // 0sam = sam - 1;sue = sue - 1;cout << "sam = " << sam << endl; // -1cout << "sue = " << sue << endl; // 65535return 0;
}
65 进制
#include<iostream>
using namespace std;
/*c++可以以三种不同的计数方式来书写整数,10.8.16c++使用前1~2位来标识数字常量的基数1. 若第一位为1~9 ->十进制2. 若第一位为0,第二位为1~7 ->八进制3. 若前两位为0x或0X ->十六进制下面的案例可以说明如上的内容注意 : 1. 默认情况下,cout以十进制格式显示整数2. 不论是几进制,计算机都是以二进制的方式存储数据如果要用cout按进制显示数据,也可以使用cout的一些特性,与endl一样,cout 提供了控制符dex hex oct分别用于十进制,十六进制和八进制*/
int main() {int num1 = 42;int num2 = 0x42;int num3 = 042;cout << "num1 = " << num1 << endl;//42cout << "num2 = " << num2 << endl;//66cout << hex << "原十六进制显示 : " << num2 << endl;//42cout << "num3 = " << num3 << endl;//34cout << oct << "原八进制显示 : " << num3 << endl; //42return 0;
}
66 **列表初始化
#include<iostream>
using namespace std;
/*潜在的数值转换问题1. 将较大的浮点数转换为较小的浮点数类型,如将double转换为float-->精度(有效数位)降低,值可能超出目标类型的取值范围,在这种情况下,结果将是不确定的2. 将浮点类型转换为整型-->小数部位丢失,原来的值去掉小数后可能超过对应整型的取值范围,结果将不确定3. 将较大的整型转换为较小的整型,如将long转换为short-->原来的值可能超出目标类型的取值范围,通常只取右边的部分*/
int main() {//1. 初始化或赋值进行的转换cout.setf(ios_base::fixed, ios_base::floatfield);float tree = 3; // int ->floatint guess(3.3983); // double -> int ,这里发生的是截取而不是四舍五入int debt = 7.2E12; cout << "tree = " << tree << endl;cout << "guess = " << guess << endl;cout << "debt = " << debt << endl;/*tree = 3.000000guess = 3debt = 1634811904*///2. 花括号转换/*以花括号{}方式初始化时进行的转换-->列表初始化,这种初始化方式通常用于给复杂的数据类型提供值列表,这种转换与上面的转换相比,要求更加严格,他不允许收缩转换,即如果接收的变量类型可能无法正确表示赋给他的值,比如将int a = (int)3212999L,就是不允许的也不允许将浮点值转换为整型*/const int code = 66;int x = 66;//char c1{ 31313 };//报错 : 从int转换到char需要收缩转换char c2 = { 66 };//允许,因为char的取值范围包括66char c3 = { code };//允许//char c4 = { x };//报错,从int到char需要收缩转换,虽然可能认为,x不是66嘛?但是编译器不会考虑到这么多,因为x是int变量//所以int -> char 是大转小,不允许//但是,如果c4采用的是常规赋值进行的转化,就可以char c4 = x;//3. 表达式中的转换/*3.1 在计算表达式的时候,c++将bool,char,unsigned char,signed char 和 short值转换为int,具体的说,true -> 1false -> 0,这些转换被称之为整型提升*/short s1 = 20;short s2 = 30;short s3 = s1 + s2;/*上述代码,在计算的时候,c++程序取到s1和s2的值,然后将他们转换为int,计算完成之后,再将结果转换为short注意 : 如果short比int短,则unsigned short 转换为 int如果两者一样长,则unsigned short 转换为 unsigned int,这样子可以保证不会丢失数据*//*3.2 不同类型进行算数运算的时候,例如int和float相加,当运算涉及到两种类型的时候,较小的类型会转换为较大的类型*/cout << sizeof(2 + 3.4); // 8return 0;
}
67 强制类型转换
#include<iostream>
using namespace std;
/**/
int main() {int num1, num2, num3;num1 = 19.99 + 11.99;num2 = (int)19.99 + (int)11.99;//c语言风格的强制类型转换num3 = int(19.99) + int(11.99);//c++语言风格的强制类型转换,这样子的目的是取值类型转换看起来就和函数调用一样cout << "num1 = " << num1 << endl;//31,因为num1的计算结果是先double类型相加,然后得到的结果通过舍去小数位转为intcout << "num2 = " << num2 << endl;//30,而num2和num3的计算是先类型转换为int然后相加,cout << "num3 = " << num3 << endl;//30char ch = 'z';cout << "the code for " << ch << " is " << int(ch) << endl;//122//c++引入的强制类型转换符,该运算符比传统取值类型转换更加严格,更加安全cout << "the code for " << ch << " is " << static_cast<int>(ch) << endl;//122return 0;
}
68 **内存分析模型
#include<iostream>
using namespace std;
/*内存分区模型 : c++程序在执行的时候,将内存大体分为四个区域1. 代码区 : 存放函数的二进制代码,由os进行管理, -- 注释不会进入代码区2. 全局区 : 存放全局变量和静态变量以及常量3. 栈区 : 由编译器自动分配释放,存放函数的参数值,局部变量等等4. 堆区 : 由程序员分配和释放,若程序员不释放,程序结束时由os回收内存四区的意义 : 不同区域存放不同的数据,赋予不同的生命周期,给我们更大的灵活编程1. 代码区: 存放 CPU 执行的机器指令 代码区是**共享**的,共享的目的是对于频繁被执行的程序,只需要在内存中有一份代码即可 代码区是**只读**的,使其只读的原因是防止程序意外地修改了它的指令 2. 全局区: 全局变量和静态变量存放在此. 全局区还包含了常量区, 字符串常量和其他常量也存放在此. ==该区域的数据在程序结束后由操作系统释放==.3. 栈区:由编译器自动分配释放, 存放函数的参数值(形参),局部变量等 注意事项:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放*/int* fun() {int a = 10;//局部变量,存放在栈区,栈区的数据在函数执行完后自动释放return &a;//返回局部变量的地址
}int* fun2() {//利用new关键字,可以将数据开辟到堆区int* p = new int(10);return p;
}int main() {//int* p = fun();//接收fun的返回值//cout << *p << endl;//第一次可以打印正确的数据,是因为编译器做了保留//cout << *p << endl;//第二次这个数据就不再保留了int* p = fun2();cout << *p << endl;cout << *p << endl;cout << *p << endl;return 0;
}
69 *new操作符
#include<iostream>
using namespace std;
/*C++中利用new操作符在堆区开辟数据 堆区开辟的数据,由程序员手动开辟,手动释放,释放利用操作符 delete 语法: new 数据类型 利用new创建的数据,会返回该数据对应的类型的指针*/int* func() {//在堆区创建一个整型数据,堆区的数据由程序员管理和释放int* p = new int(10);return p;
}void test01() {int* p = func();cout << *p << endl;cout << *p << endl;//如果想释放堆区的数据,利用关键字deletedelete p;//内存已经被释放,再次访问就是非法操作,会报错//cout << *p << endl;
}void test02() {//在堆区创建大小为10的整型数组int* arr = new int[10];//注意,这里是方括号,不是圆括号,方括号里的10代表数组的大小为10,而圆括号里面的10代表值为10for (int i = 0; i < 10; i++){arr[i] = i + 100;}for (int i = 0; i < 10; i++){cout << arr[i] << endl;}//释放堆区的数组,但是要注意,这里和释放变量不一样delete[] arr;
}
int main() {test01();//10test02();return 0;
}
70 引用的基本使用
#include<iostream>
using namespace std;
/*引用的基本使用作用 : 给变量起别名语法 : 数据类型 &别名 = 原名引用vs指针1. 不存在空引用,引用必须知道一个合法的内存空间,但是指针存在空指针和野指针2. 一旦引用初始化为一个对象,就不可以指向另一个对象,所以,引用和常指针很像.指针可以在任何时候指向到另一个对象,引用指向对象的值是可以修改的3. 引用必须在创建的时候就初始化,指针可以在任何时间初始化
*/
int main() {int a = 10;int& b = a;b = 20;cout << "a = " << a << endl;return 0;
}
71 引用做函数参数
#include<iostream>
using namespace std;
/*引用做函数参数1. 作用 : 函数传参的时候,可以利用引用技术,让形参修饰实参(也就是形参改变,实参也改变,类似地址传递)2. 优点 : 可以简化指针引用一般用在做函数参数的情况比较多,通过引用参数产生的效果和使用地址传递的效果是一样的,引用的语法更清楚简单
*///交换
//引用传递
void swap1(int& num1, int& num2) {int temp = num1;num1 = num2;num2 = temp;
}
//地址传递
void swap2(int* p1, int* p2) {int temp = *p1;*p1 = *p2;*p2 = temp;
}
//值传递
void swap3(int num1, int num2) {int temp = num1;num1 = num2;num2 = temp;
}
int main() {int num1 = 10;int num2 = 20;//使用引用传递swap1(num1, num2);cout << "num1 = " << num1 << endl;//20cout << "num2 = " << num2 << endl;//10//使用地址传递swap1(num1, num2);cout << "num1 = " << num1 << endl;//10cout << "num2 = " << num2 << endl;//20//使用值传递swap1(num1, num2);cout << "num1 = " << num1 << endl;//10cout << "num2 = " << num2 << endl;//20return 0;
}
72 引用做函数返回值
#include<iostream>
using namespace std;
/*引用做函数返回值1. 作用 : 引用是可以作为函数的返回值的2. 注意 : 不要返回局部变量引用3. 语法 : 函数调用作为左值因为函数返回的是一个引用,所以我们可以把函数放到赋值语句的左边
*/
double vals[] = { 10.1, 12.6, 33.1, 24.1, 50.0 };double& setValue(int i) {double& ref = vals[i];return ref;//返回的是下标为i的元素的引用,ref是一个引用变量,ref引用vals[i],最后在返回shit
}
//当函数返回一个引用的时候,要注意被引用的对象不可以超出作用域,所以返回一个局部变量的引用是不合法的,但是,可以返回一个
//对静态变量的引用
int& setNum1() {int num1;return num1;
}
int& setNum2() {static int a = 10;//静态变量,存放在全局区,全局区上的数据在程序结束后由系统释放return a;
}
int main() {int len = sizeof(vals) / sizeof(vals[0]);cout << "改变前 : " << endl;for (int i = 0; i < len; i++){cout << "vals[ " << i << " ] = " << vals[i] << endl;}setValue(1) = 12;setValue(3) = 13;cout << "改变后 : " << endl;for (int i = 0; i < len; i++){cout << "vals[ " << i << " ] = " << vals[i] << endl;}return 0;
}
73 引用和指针
#include<iostream>
using namespace std;
/**/
int main() {int b = 0;int& a = b;a = 4;cout << "a = " << a << endl; // 4cout << "b = " << b << endl; // 4int* p = &b;b = 100;cout << "a = " << a << endl; // 100cout << *p << endl; // 100return 0;
}
74 *引用的本质
#include<iostream>
using namespace std;
/*引用的本质本质 : 引用的本质在c++内部实现是一个指针常量 (指针的指向不可以修改,值可以修改)
*/
//发现是引用,转换为 int* const ref = &a;
void func(int& ref) {ref = 100; // ref是引用,转换为*ref = 100
}
int main() {int a = 10;//自动转换为 int* const ref = &a; 指针常量是指针指向不可改,也说明为什么引用不可更改int& ref = a;ref = 20; //内部发现ref是引用,自动帮我们转换为: *ref = 20;cout << "a:" << a << endl;cout << "ref:" << ref << endl;func(a);return 0;
}
75 常量引用
#include<iostream>
using namespace std;
/*常量引用作用 : 常量引用主要用来修饰形参,防止误操作在函数形参列表中,可以加const修饰形参,防止形参变实参
*///打印数据的函数
void showValue(const int& val) {//val = 1000;//报错 : 表达式必须是可修改的左值cout << "val = " << val << endl;
}int main() {//int a = 10;//int& ref = 10;// 引用必须引用一块合法的空间//const int& ref = 10;// 但是这样子就是正确的,加上const之后,编译器将代码,修改为/*int temp = 10;const int& ref = temp;这样子就合法了*///ref = 20;//会报错:表达式必须是可修改的左值,这里的ref既不能修改指向,也不可以修改值,变为只读状态int a = 100;showValue(a);cout << "a = " << a << endl;return 0;
}
76 函数默认参数
#include<iostream>
using namespace std;
/*函数默认参数在c++中,函数的参数列表中的形参是可以有默认值的语法 : 返回值类型 函数名 (参数 = 默认值) {}注意 : 1. 假设参数列表的第n个参数加上了默认值,那么之后的参数也必须加上默认值2. 函数声明和函数实现只能有一个有默认值
*/
int func(int a, int b = 20, int c = 30);
int func(int a, int b, int c) {return a + b + c;
}
int main() {//int sum = func(1, 2, 3);int sum = func(10);cout << sum << endl;//60 return 0;
}
77 *函数重载
#include<iostream>
using namespace std;
/*函数重载作用 : 函数名称可以相同,提高复用性函数重载满足条件 : 1. 同一个作用域2. 函数名称相同3. 函数参数类型不同,或者个数不同或者顺序不同注意 : 函数的返回值不可以作为函数重载的条件,也就是函数重载和返回值无关
*/void func() {cout << "func的调用" << endl;
}
//void func() {//这时候会运行失败,因为main不知道该调用哪个func函数,这两个func不满足函数重载的要求
// cout << "func的调用!" << endl;
//}
void func(int a) {cout << "a = " << a << endl;
}
void func(double d) {cout << "d = " << d << endl;
}
void func(int num1, int num2) {cout << "int num1 = " << num1 << "|| int num2 = " << num2 << endl;
}
void func(int num1, double num2) {cout << "int num1 = " << num1 << "|| double num2 = " << num2 << endl;
}
void func(double num1, int num2) {cout << "double num1 = " << num1 << " || int num2 = " << num2 << endl;
}
//int func(double num1, int num2) {//报错 : 无法重载仅用返回值类型区分的函数
// cout << "double num1 = " << num1 << " || int num2 = " << num2 << endl;
//}
int main() {func();func(3);func(3, 2.0);func(2, 3);func(2.0, 3);return 0;
}
78 函数重载注意事项
#include<iostream>
using namespace std;
/*1. 引用作为重载条件const int& 和 int& 属于类型不同2. 函数重载碰到函数默认参数
*///1. 引用作为重载条件
void func(int& a) {//也属于函数重载cout << "func(int& a) 调用" << endl;
}
void func(const int& a) {cout << "func(const int& a) 调用" << endl;
}//2. 函数重载遇到函数默认参数
void func2(int a,int b = 10) {cout << "func2(int a, int b = 10) 的调用" << endl;
}
void func2(int a) {cout << "func2(int a) 的调用" << endl;
}int main() {int a = 10;func(a);//func(int& a) 调用 , 因为传入的是变量,可读可写,而const修饰后变成只读的了,所以会调用没有const修饰的func(10);//func(const int& a) 调用/*首先分析,如果调用的是第一个函数,那么等同于代码int& a = 10;这是错误的,因为引用必须指向合法的内存空间如果调用的是第二个函数const int& a = 10;然后编译器会帮助我们进行代码优化,变为 : int temp = 10;const int& a = temp;就是正确的了*///func2(10);//会报错,出现了二义性,两个func2函数都可以调用,所以在函数有默认参数的时候要注意,函数重载的时候就尽量不要默认参数了return 0;
}
79 类和对象概述
#include<iostream>
using namespace std;
/*类和对象c++面向对象的三大特性为:1. 封装2. 继承3. 多态c++认为万事万物皆是对象,对象上有其属性和行为类是用户定义的类型,但是作为用户,我们并没有设计ostream和istream类,就像函数可以来自函数库一样,类也可以来自类库
*/
int main() {return 0;
}
80 封装
#include<iostream>
using namespace std;
/*封装意义 : 1. 将属性和行为作为一个整体,表现生活中的事物2. 将属性和行为的权限加以控制语法 : class 类名{ 访问权限: 属性/行为 };
*/
#define PI 3.14class circle
{
public://访问权限,公共的权限//属性int r;//半径//行为double caculateZC(){return 2 * PI * r;}};
int main() {circle c;//实例化一个对象c.r = 10;//给对象的属性赋值cout << c.caculateZC() << endl;//62.8return 0;
}
81 案例
#include<iostream>
using namespace std;
/*设计一个学生类,属性有姓名和学号,可以给姓名和学号赋值,可以显示学生的姓名和学号
*/class student
{
public://属性string name;string id;public:void setName(string s_name) {name = s_name;}void setId(string s_id) {id = s_id;}void toString() {cout << "name = " << name << endl;cout << "id = " << id << endl;}
};int main() {student s1;s1.setId("20171611607");s1.setName("何佳乐");s1.toString();return 0;
}
82 权限控制
#include<iostream>
using namespace std;
/*封装意义2 : 类在设计的时候,可以把属性和行为放在不同的权限下,加以控制访问权限有3种1. public 公共权限 类内可以访问,类外可以访问2. protected 保护权限 类内可以访问,类外不可以访问3. private 私有权限 类内可以访问,类外不可以访问protected 和 private 的区别在继承会提到,这里简单说一下,就是继承的时候,子类的成员函数可以访问父类中保护权限的内容但是子类不可以访问父类中的私有内容
*/class person
{
public:string name;//姓名,公共权限
protected:string car; //汽车,保护权限
private:int password;//密码,私有权限public:void func(){name = "zhangsan";car = "拖拉机";password = 123456;}void toString() {cout << "name = " << name << endl;cout << "car = " << car << endl;cout << "password = " << password << endl;}
};
int main() {person p;p.func();p.name = "何佳乐";//这里,p打点后发现car 和 password是不可以访问的,因为私有权限和保护权限,类外不可以访问p.toString();return 0;
}
83 struct 和 class的区别
#include<iostream>
using namespace std;
/*c++中struct和class的区别(唯一)1. struct默认权限为公共2. class 默认权限为私有
*/class C1
{int m_A;//默认权限是私有,外部类无法访问
};
struct C2
{int m_B;//默认权限是公共
};
int main() {C1 c1;//cout << c1.m_A << endl;//报错,不可访问C2 c2;c2.m_B = 100;cout << c2.m_B << endl;return 0;
}
84 成员属性设置为私有
#include<iostream>
using namespace std;
/*成员属性设置为私有1. 可以自己控制读写权限2. 对于写可以检测数据的有效性
*/class Person
{
private:string name;// 读写int age = 20; // 只读,写的年龄必须在0~100之间string lover;//只写
public:void setName(string s_name){name = s_name;}string getName(){return name;}int getAge(){return age;}void setLover(string s_lover){lover = s_lover;}void setAge(int s_age) {if (s_age >150 || s_age < 0){cout << "请输入合法的年龄" << endl;return;}age = s_age;}
};
int main() {Person p;p.setName("zhangsan");cout << "name = " << p.getName() << endl;cout << "age = " << p.getAge() << endl;p.setLover("lisi");p.setAge(50);cout << "age = " << p.getAge() << endl;return 0;
}
85 案例 : 立方体
#include "Cube.h"
/*设计立方体类(Cube)1. 求出立方体的面积和体积2. 分别用全局函数和成员函数判断两个立方体是否一样
*/
//class Cube
//{
//private:
// int m_H;
// int m_L;
// int m_W;
//public:
// int getH(){
// return m_H;
// }
// int getW() {
// return m_W;
//
// }
// int getL() {
// return m_L;
// }
// void setH(int h)
// {
// m_H = h;
// }
// void setL(int l)
// {
// m_L = l;
// }
// void setW(int w)
// {
// m_W = w;
// }
// int getArea()
// {
// return (m_H * m_L + m_H * m_W + m_L * m_W) * 2;
// }
// int getVolume()
// {
// return m_H * m_L * m_W;
// }
// bool isEqual(Cube cube)
// {
// if (m_H == cube.getH() && m_W == cube.getW() && m_L == cube.getL())
// {
// return true;
// }
// return false;
// }
//
//};
int main() {Cube cube;cube.setH(10);cube.setW(10);cube.setL(10);Cube cube2;cube2.setH(10);cube2.setW(10);cube2.setL(10);cout << "area = " << cube.getArea() << endl;cout << "volume = " << cube.getVolume() << endl;cout << cube.isEqual(cube2);return 0;
}
86 案例 : 点和圆的关系,分文件编写
#include "Circle.h"
/*设计一个圆形类(Circle),和一个点类(Point),计算点和圆的关系。
*/int main() {Circle c;c.c_x = 0;c.c_y = 0;c.c_r = 10;Point p;p.p_x = 10;p.p_y = 10;c.getRelation(p);c.test(p);cout << p.p_x << endl;cout << &p << endl;return 0;
}
- Circle.h
#pragma once
#include "Point.h"
class Circle
{
public:int c_x;int c_y;int c_r;void getRelation(Point p);void test(Point& p);
};
- Circle.cpp
#include "Circle.h"void Circle::getRelation(Point p)
{double distance = sqrt(pow(p.p_x - c_x, 2) + pow(p.p_y - c_y, 2));if (distance < c_r){cout << "点在圆内" << endl;return;}else if (distance == c_r) {cout << "点在圆上" << endl;}else {cout << "点在圆外" << endl;}
}
void Circle::test(Point& p) {p.p_x = 100;
}
87 构造函数和析构函数
#include<iostream>
using namespace std;
/*对象的**初始化和清理**也是两个非常重要的安全问题 一个对象或者变量没有初始状态,对其使用后果是未知 同样的使用完一个对象或变量,没有及时清理,也会造成一定的安全问题c++利用了**构造函数**和**析构函数**解决上述问题,这两个函数将会被编译器自动调用,完成对象初始化和清理工作。对象的初始化和清理工作是编译器强制要我们做的事情,因此如果**我们不提供构造和析构,编译器会提供****编译器提供的构造函数和析构函数是空实现。*** 构造函数:主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用。* 析构函数:主要作用在于对象**销毁前**系统自动调用,执行一些清理工作。构造函数 :类名(){}1. 没有返回值也不用写void2. 函数名称与类名相同3. 构造函数可以有参数,所以可以发生重载4. 程序在调用对象的时候会自动调用构造,无需手动调用,而且只会调用一次析构函数 : ~类型(){}1. 析构函数没有返回值也不写void2. 函数名称与类名相同,在名称前面加上符号~3. 析构函数不可以有参数,因此不可以发生重载4. 程序在对象销毁前会自动调用析构,无需手动调用,而且只会调用一次
*/class Person
{
public://构造函数Person() {cout << "构造函数的调用" << endl;}//析构函数~Person() {cout << "析构函数调用" << endl;}
};void test01() {Person p;//构造函数和析构函数自动调用
}int main() {//test01();Person p;//代码走到这里,person不会执行析构函数,因为没有执行到return 0;system("pause");return 0;
}
88 *构造函数的分类和调用
#include<iostream>
using namespace std;
/*构造函数的分类和调用1. 两种分类方式1. 按参数分 : 有参构造和无参构造2. 按类型分 : 普通构造和拷贝构造2. 三种调用方式1. 括号法2. 显示法3. 隐式转换法额外知识 : 匿名对象
*/class Person
{
public:int age;
public://无参构造函数,也叫做默认构造,因为如果用户没有写构造函数,那么编译器会自动帮助我们加上一个无参构造函数,并且实现为空Person() {cout << "Person的构造函数调用" << endl;}//有参构造函数Person(int a) {age = a;cout << "Person的有参构造函数调用 a = " << a << endl;}//上面的两个构造函数也可以称之为普通构造函数/*拷贝构造函数,他的作用是将参数p赋值给当前的对象加const是为了防止修改原p,比较我们是以p为样本,总不能复制完还把样本p修改了加引用是为了节省地址空间*/ Person(const Person& p) {cout << "Person的拷贝构造函数调用" << endl;age = p.age;}//析构函数~Person() {cout << "Person的析构函数调用" << age << endl;}
};//构造函数的调用
void test01()
{//1. 括号法Person p;//调用默认构造函数Person p2(10);//调用有参构造函数//拷贝构造函数Person p3(p2);/*注意事项 :1. 调用默认构造函数的时候,不要加小括号Person p();因为编译器将上面的代码视作函数的声明,不会创建对象*/cout << "p2.age = " << p2.age << endl; // 10cout << "p3.age = " << p3.age << endl; // 10cout << "-----------------------" << endl;Person(30);//匿名对象,这一行结束就释放/*注意事项 :不要利用拷贝构造函数来初始化一个匿名对象Person(p3)编译器会认为是Person p3;所以会导致p3重定义*///2. 显示法Person p4;Person p5 = Person(20); // 调用有参构造//显示法调用拷贝构造Person p6 = Person(p5);cout << "-----------------------" << endl;//3. 隐式转换法Person p7 = 40; // 编译器会将该代码转换为 : Person p7 = Person(40);Person p8 = p7; // 拷贝构造,编译器会将该代码转换为 : Person p8 = Person(p7)}int main() {test01();return 0;
}
89 拷贝构造函数的调用时机
#include<iostream>
using namespace std;
/*拷贝构造函数的调用时机c++中,拷贝构造函数的调用时机通常有三种情况1. 使用一个已经创建完毕的对象来初始化一个新对象2. 值传递的方式给函数传递值3. 以值方式返回局部对象
*/class Person
{
public:int mAge;
public:Person(){cout << "无参构造函数!" << endl;mAge = 0;}Person(int age){cout << "有参构造函数!" << endl;mAge = age;}Person(const Person& p){cout << "拷贝构造函数!" << endl;mAge = p.mAge;}~Person(){cout << "析构函数" << endl;}
};//1. 使用一个已经构造完毕的对象来初始化一个对象
void test01()
{Person p1 = Person(20);Person p2 = Person(p1);//拷贝构造p2cout << "p2.mAge = " << p2.mAge << endl; // 20}
//2. 值传递的方式给函数参数传值
void doWork(Person w_p)
{}
void test02()
{Person p3;doWork(p3);/*值传递其实就是构造函数隐式写法相当于代码:Person w_p = p3;*/
}
//3. 值方式返回局部对象
Person doWork2()
{Person p4;cout << &p4 << endl;return p4;
}
void test03()
{Person p5 = doWork2();cout << &p5 << endl;
}
int main() {//test01();//test02();test03();return 0;
}
90 **构造函数的调用规则
#include<iostream>
using namespace std;
/*构造函数的调用规则默认情况下,c++至少给一个类添加三个函数1. 默认构造函数(无参,函数体为空)2. 默认析构函数(无参,函数体为空)3. 默认拷贝构造函数,对属性值进行拷贝构造函数调用规则如下1. 如果用户定义有参构造函数,c++不再默认提供无参构造,但是会提供默认拷贝构造2. 如果用户定义拷贝构造函数,c++不会再提供其他构造函数
*/class Person
{
public:int mAge;
public:Person(){cout << "无参构造函数!" << endl;mAge = 0;}Person(int age){cout << "有参构造函数!" << endl;mAge = age;}/*Person(const Person& p){cout << "拷贝构造函数!" << endl;mAge = p.mAge;}*/~Person(){cout << "析构函数" << endl;}
};void test01()
{Person p1(18);Person p2(p1);cout << "p2.age = " << p2.mAge << endl;
}
int main() {test01();return 0;
}
91 ***深拷贝和浅拷贝
#include<iostream>
using namespace std;
/*深拷贝与浅拷贝是面试经常问到的,也是常见的一个坑浅拷贝 : 简单的赋值拷贝操作深拷贝 : 在堆区重新申请空间,进行拷贝操作总结 : 如果数据有在堆区开辟的,一定要自己提供拷贝构造函数而不是依靠编译器默认实现,防止浅拷贝带来的问题
*/class Person
{
public:int m_age;int* m_height;
public:Person(){cout << "Person的默认无参构造函数调用" << endl;}Person(int age,int height){m_age = age;m_height = new int(height);//将height通过new创建在堆区,堆区的数据由程序员手动开辟,也由程序员手动关闭cout << "Person的默认有参构造函数调用" << endl;}/*这里,析构函数第一次有了真正的作用,就是在对象销毁前,关闭用户在堆区创建的有关数据但是,这里的代码会出现错误 : 堆区的内容重复释放因为我们的Person类有个int型指针变量height,那么由于p2 是基于p1的浅拷贝,所以p1指针和p2指针存储的是同一个地址单元,那么在delete的时候就会出错,函数内由栈实现,所以是先进后出,p2先执行析构函数中的delete代码,对该地址空间进行了delete,但是之后p1也会执行析构函数,对该地址空间进行delete,所以一个空间进行多次delete操作就会报错所以,浅拷贝的问题,要由深拷贝解决,自己写一个拷贝构造函数,解决浅拷贝带来的问题我们拷贝的时候,再堆区重新申请一个地址空间,存储和p1的height一样的数值,那么这个时候,p1和p2指向不同的地址空间,但是地址空间内的值是一样的*/~Person(){if (m_height != NULL){delete(m_height);m_height = NULL;}cout << "默认析构函数调用" << 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);//然后代码就可以正常实现了}};void test01()
{Person p1(18,160);cout << "p1.age = " << p1.m_age << " || p1.height = " << *p1.m_height << endl;//18Person p2(p1);cout << "p2.age = " << p2.m_age << " || p2.height = " << *p2.m_height << endl;//18p1.m_age = 20;cout << "p1.age = " << p1.m_age << " || p1.height = " << *p1.m_height << endl;//20cout << "p2.age = " << p2.m_age << " || p2.height = " << *p2.m_height << endl;//18/*这里不一样,是因为我们的Person没有提供默认拷贝构造函数,所以编译器会默认创建一个拷贝构造函数,这个构造函数实现的是值拷贝*/}int main() {test01();return 0;
}
92 初始化列表
#include<iostream>
using namespace std;
/*初始化列表作用 : c++提供了初始化语法列表,原来初始化属性语法 : 构造函数():属性名1(属性值1),属性名2(属性值2),属性名3(属性值3)..{}
*/class Person
{
public:int m_A;int m_B;int m_C;
public://传统的初始化操作/*Person(int a, int b, int c){m_A = a;m_B = b;m_C = c;}*///初始化列表初始化属性Person(int a, int b ,int c) :m_A(a), m_B(b), m_C(c){}};void test01()
{//Person p(10, 20, 30);Person p(30,20,10);cout << "a = " << p.m_A << endl;cout << "b = " << p.m_B << endl;cout << "c = " << p.m_C << endl;
}int main() {test01();return 0;
}
93 类对象作为类成员
#include<iostream>
using namespace std;
/*类对象作为类成员两者构造函数和析构函数的调用顺序1. 首先,先调用类对象的构造函数,然后调用本类的构造函数2. 先调用本类的析构函数,然后调用类对象的析构函数
*/class A
{
public:int num1 = 10;
public:A() {cout << "A的无参构造函数" << endl;}~A() {cout << "A的析构函数" << endl;}
};
class B
{
public:A a;
public:B() {cout << "B的无参构造函数" << endl;}~B() {cout << "B的析构函数" << endl;}
};int main() {B b;cout << b.a.num1 << endl;return 0;
}
94 静态成员变量
#include<iostream>
using namespace std;
/*静态成员就是在成员变量和成员函数前加上关键字static,称为静态成员静态成员分为1. 静态成员变量1. 所有对象共享同一份数据,整个内存就这么一份数据2. 在编译阶段分配内存,不是创建对象的时候分配,分配的内存位于全局区3. 类内声明,类外初始化2. 静态成员函数1. 所有对象共享同一个函数2. 静态成员函数只可以访问静态成员变量
*/class Person
{
public://所有对象都共享同一份数据static int m_a;//类内声明/*静态成员变量,也是有访问权限的*/
private:static int m_b;
};
int Person::m_a = 100;//类外初始化,如果不写Person::,编译器会认为这是一个全局变量,而不是静态变量
int Person::m_b = 200;
void test01()
{Person p;cout << p.m_a << endl;//100Person p2;p2.m_a = 200;cout << p.m_a << endl;//200cout << p2.m_a << endl;//200
}
void test02()
{//静态成员变量,不属于某一个对象,所以所有对象共享同一份数据//因此,静态成员变量有两种访问方式//1. 通过对象进行访问Person p3;cout << p3.m_a << endl;//100//2. 通过类名进行访问cout << Person::m_a << endl;//100//cout << Person::m_b << endl;//报错,显示不可访问
}
int main() {//test01();test02();return 0;
}
95 静态成员函数
#include<iostream>
using namespace std;
/*静态成员函数1. 所有对象共享同一个函数2. 静态成员函数只可以访问静态成员变量因为静态成员属性的创建比成员属性的早,你要访问一个还没有开辟空间的数据,肯定是不可以的
*/class Person
{
public:int m_a = 100;//非静态成员变量static int m_b;//静态成员变量
public://静态成员函数,并且静态成员函数也是有访问权限的,也可以设置权限为public,private和protectedstatic void func(){//cout << "m_a = " << m_a;//报错,静态成员函数只可以访问静态成员变量cout << "m_b = " << m_b << endl;//可以运行,因为m_b是静态成员变量cout << "static void func调用" << endl;}
};
int Person::m_b = 200;//类外初始化
void test01()
{//1. 通过对象访问Person p;p.func();//2. 通过类名访问Person::func();
}int main() {test01();return 0;
}
96 成员函数和成员变量分开存储
#include<iostream>
using namespace std;
/*在c++中,类内的成员变量和成员函数分开存储只有非静态变量才属于类的对象上
*/class Person
{
//public://非静态成员变量占据对象的空间int m_A;//静态成员变量不占对象空间static int m_B;//非静态成员函数void func() {};//静态成员变量static void func2() {};
//public:
// Person()
// {
// m_A = 0;
// }
};
int Person::m_B = 100;
void test01()
{Person p;//空对象占用的内存空间为 1 /*因为c++编译器会给每个空对象分配一个字节的空间,是为了区分空对象占内存的位置,因为如果不分配空间,那么如果有多个空对象,编译器就无法区分他们了,至于为什么分配1个字节,肯定是分配越少越好,毕竟只是为了区分,没必要分配太多空间*///接下来,如果类有一个成员变量 int m_A;则占用的空间为4//接下来,类再加上一个静态成员变量static int m_B;则占用空间还是4,因为静态成员不属于对象,不占用对象的空间/*接下来, 再加上一个函数, 占用的空间还是4, 因为成员变量和成员函数是分开存储的, 也不属于类的对象上,并且, 其实非静态成员函数也是只有一个,这方面的内容97讲*/cout << "size of p = " << sizeof(p) << endl;// 1
}
int main() {test01();return 0;
}
97 this指针
#include<iostream>
using namespace std;
/*this指针通过96的代码,我们可以直到成员变量和成员函数是分开存储的,每一个非静态成员函数只会诞生一份函数实例,也就是说,多个类型的对象会共用一块代码那么问题是 : 这一块代码是如何区分是类的哪个对象调用自己的呢?c++通过提供特殊含义的指针 : this指针,解决上述问题,this指针指向被调用的成员函数所属的对象this指针是隐含每一个非静态成员函数内的一种指针this指针无需定义,直接使用即可this指针的用途:1. 当形参和成员变量同名的时候,可以用this指针来区分2. 在类的非静态成员函数中返回对象本身,可以使用return *this;this指针的本质是一个常指针,指针的指向是不可以修改的
*/class Person
{
public:int age;
public:Person(int age){this->age = age;}Person& addAge(Person p){this->age += p.age;//this指向p2的指针,而*this指向的就是p2对象本体return *this;}
};
//方式命名冲突
void test01()
{Person p1(18);cout << "age = " << p1.age << endl;
}
//返回对象本身
void test02()
{Person p1(10);Person p2(20);p2.addAge(p1).addAge(p1).addAge(p1).addAge(p1);/*在这里,如果addAge返回值是Person,那么cout输出为30,因为返回的Person是一个新的对象,只不过新的对象值和p2一样是30,每次addAge返回的都是一个新对象,如果我们用Person p3接收上面链式编程的返回值,那么p3.age = 60但是如果输出p2.age,由于p2.age只执行了链式编译的第一个addAge,之后的addAge都是新Person执行的,所以cout输出为30如果返回的是Person&,那么相当于 Person& p3 = p2.addAge;那么p3其实指向的就是p2,那么之后继续执行addAge,返回的都是p2的引用,修改的自然也就是p2的age,所以cout输出为60*/cout << "p2.age = " << p2.age << endl;}
int main() {//test01();test02();return 0;
}
98 空指针访问成员函数
#include<iostream>
using namespace std;
/*空指针访问成员函数c++中,空指针也是可以调用成员函数的,但是也要注意有没有用到this指针如果用到this指针,需要加以判断,以保持代码的健壮性
*/class Person
{
public:int m_Age = 10;
public:void showClassNama(){cout << "this is person class " << endl;}void showPersonAge(){//cout << "age = " << m_Age << endl; // 访问异常,在c++中,我们会默认的在m_Age前面加上this,而this是nullperif (!this)//这样子可以提高代码的健壮性{cout << "传入的指针为空" << endl;return;}cout << "age = " << this->m_Age << endl;}};void test01()
{Person* p = new Person();p->m_Age = 19;p->showClassNama();p->showPersonAge();
}
int main() {test01();return 0;
}
99 **const修饰成员函数&mutable
#include<iostream>
using namespace std;
/*const修饰成员函数1. 常函数1. 成员函数后加const我们称这个函数为常函数2. 常函数内不可以修改成员属性3. 成员属性声明时加关键字mutable,在常函数中依然可以修改2. 常对象1. 声明对象前加const称该对象为常对象2. 常对象只可以调用常函数
*/class Person
{
public:void showPerson() const{//m_A = 100; //报错 : 表达式必须是可修改的左值m_B = 100; //当成员属性声明的时候加上关键字mutable,就可以在常函数中修改,也可以被常对象修改}void func(){}
public:mutable int m_B;int m_A;
};void test01()
{Person p;p.showPerson();
}
void test02()
{const Person p; //在对象前加const,变为常对象//p.m_A = 100; //报错,常对象只可以调用常函数和mutable成员属性p.m_B = 100; p.showPerson();//p.func(); //报错,常对象只可以调用常函数,因为普通成员函数可以修改属性,所以矛盾
}
int main() {return 0;
}
100 全局函数做友元
#include<iostream>
using namespace std;
/*友元 :在程序里,有些 私有属性,也希望让类外特殊的一些函数或者类进行访问,就需要用到友元的技术友元的目的就是让一个函数或者类 访问另一个类中的私有成员友元的关键字为 : friend友元的三种实现 : 1. 全局函数做友元2. 类做友元3. 成员函数做友元
*/class Building
{friend void goodGay(Building& b);//现在,goodGay函数就可以访问Building类的私有成员
public:Building(){m_SittingRoom = "客厅";m_BedRoom = "卧室";}
public:string m_SittingRoom; //客厅
private:string m_BedRoom; //卧室};
//全局函数
void goodGay(Building& b)
{cout << "好基友的全局函数 正在访问 : " << b.m_SittingRoom << endl;cout << "好基友的全局函数 正在访问 : " << b.m_BedRoom << endl;
}
void test01()
{Building b;goodGay(b);
}
int main() {test01();return 0;
}
101 类做友元
#include<iostream>
using namespace std;
/*类做友元
*/
class Building;
class GoodGay
{
public:void visit();//参观,访问build中的属性,不可以访问私有属性void visit2();//参观,访问build中的属性,可以访问私有属性
public:GoodGay();
public:Building* b;//这里不可以是Building& b 因为引用必须初始化};
class Building
{//friend class GoodGay;friend void GoodGay::visit2();
public:Building();
public:string m_SettingRoom;//客厅
private:string m_BedRoom;//卧室
};//类外写成员函数
Building::Building() {m_SettingRoom = "客厅";m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{b = new Building();}
void GoodGay::visit()
{cout << "好基友正在访问 : " << b->m_SettingRoom << endl;
}
void GoodGay::visit2()
{cout << "好基友正在访问 : " << b->m_SettingRoom << endl;cout << "好基友正在访问 : " << b->m_BedRoom << endl;
}
void test01()
{GoodGay g;g.visit();
}
void test02()
{GoodGay g;g.visit2();
}
int main() {//test01();test02();return 0;
}
102 +运算符重载
#include<iostream>
using namespace std;
/*运算符重载 : 对已经有的运算符重新进行定义,赋予其另外一种功能,以适应不同的数据类型注意:1. 对于内置的数据类型的表达式的运算符是不可能改变的 比如通过运算符重载实现int 1 + int 2 = 100;是不可能的2. 不要滥用运算符重载
*/class Person
{
public:int m_A;int m_B;Person() {}Person(int a, int b) {m_A = a;m_B = b;}//成员函数实现 + 号运算符重载Person operator+(const Person& p) {Person temp;temp.m_A = this->m_A + p.m_A;temp.m_B = this->m_B + p.m_B;return temp;}
};
//全局函数做运算符重载
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(10, 20);Person p2(20, 30);/*本质是Person p3 = p1.operator+(p2)*/Person p3 = p1 + p2;cout << "p3.a = " << p3.m_A << endl;cout << "p3.b = " << p3.m_B << endl;
}
void test02()
{Person p1(10, 20);Person p2(20, 30);/*本质是Person p3 = operator+(p1 , p2)*/Person p3 = p1 + p2;//简化后cout << "p3.a = " << p3.m_A << endl;cout << "p3.b = " << p3.m_B << endl;//调用重载的函数Person p4 = p1 + 100;cout << "p4.a = " << p4.m_A << endl;cout << "p4.b = " << p4.m_B << endl;
}
int main() {//test01();test02();return 0;
}
103 左移运算符重载
#include<iostream>
using namespace std;
/*左移<<运算符重载
*/class Person
{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;//利用成员函数重载左移运算符/*我们一般不适用成员函数重载左移运算符,不是不可以,而是无法达到需要的cout << p样式*//*void operator<<(Person& p){}*/
};
//全局函数重载,本质就是cout << p
ostream& operator<<(ostream& cout, Person& p)
{cout << "m_A = " << p.m_A << endl;cout << "m_B = " << p.m_B << endl;return cout;
}
void test01()
{Person p(10,10);//cout << p << endl;//报错 : 没有与这些操作数匹配的左移运算符,无法链式编程,所以返回对象类型必须是ostreamcout << p << endl << "helloworld" << endl;}int main() {test01();return 0;
}
104 递增运算符重载
#include<iostream>
using namespace std;
/*递增运算符重载 ++作用 : 通过重载递增运算符,实现自己的整型数据
*///自定义整型
class MyInteger
{friend ostream& operator<<(ostream& cout, const MyInteger& myint);//友元
private:int m_Num;
public:MyInteger(){m_Num = 0;}//重载后置++运算符/*这里注意,和重载前置不同,这里我们的返回值是MyInteger而不是MyInteger&,因为如果这里我们返回MyInteger&,就导致我们返回了一个局部对象的引用,局部对象在当前函数执行完之后就销毁了,所以后面的操作都是违法操作*/MyInteger operator++(int){MyInteger temp = *this;this->m_Num++;return temp;}//重载前置++运算符MyInteger& operator++(){m_Num++;return *this;}
};//返回类型是ostream&,是为了可以实现链式编程
ostream& operator<<(ostream& cout, const MyInteger& myint)
{cout << myint.m_Num << endl;return cout;
};void test01()
{MyInteger myint;cout << ++++myint << endl;
}
void test02() {MyInteger myint;cout << myint++ << endl;cout << myint << endl;
}
int main() {//test01();test02();return 0;
}
105 *赋值运算符重载
#include<iostream>
using namespace std;
/*赋值运算符重载c++编译器至少给一个类添加4个函数1. 默认构造函数(无参,函数体为空)2. 默认析构函数(无参,函数体为空)3. 默认拷贝构造函数,对属性进行值拷贝4. 赋值运算符 operator=, 对属性进行值拷贝(因为是值拷贝,所以如果有属性创建在堆区,就会引发深浅拷贝的问题)
*/class Person
{
public:int* m_A;
public:Person(int age){m_A = new int(age);}~Person(){if (m_A!=NULL){delete(m_A);m_A = NULL;}}//重载赋值运算符Person& operator=(const Person& p){//编译器提供的是浅拷贝//我们应该提供的是深拷贝if (m_A != NULL){delete(m_A);m_A = NULL;}m_A = new int(*p.m_A);return *this;}
};void test01()
{Person p1(18);Person p2(20);Person p3(30);cout << "p1.age = " << *p1.m_A << endl;//18cout << "p2.age = " << *p2.m_A << endl;//20p3 = p2 = p1;cout << "p1.age = " << *p1.m_A << endl;//18cout << "p2.age = " << *p2.m_A << endl;//18cout << "p3.age = " << *p3.m_A << endl;//18
}int main() {test01();return 0;
}
106 关系运算符重载
#include<iostream>
using namespace std;
/*关系运算符重载作用 : 重载关系运算符,可以让两个自定义类型对象进行对比操作
*/class Person
{
public:int age;
public:Person(int age) {this->age = age;}bool operator==(const Person& p) {if (this->age == p.age){return true;}else {return false;}}bool operator!=(const Person& p) {if (this->age != p.age){return true;}else {return false;}}
};
void test01()
{Person p1(18);Person p2(19);cout << "p1 == p2 ? " << (p1 == p2) << endl;cout << "p1 != p2 ? " << (p1 != p2) << endl;
}
int main() {test01();return 0;
}
107 函数调用运算符重载
#include<iostream>
using namespace std;
/*函数调用运算符重载1. 函数调用运算符()也可以重载2. 由于重载后的使用方式非常像函数的调用,因此称之为仿函数 3. 仿函数没有固定的写法,非常灵活
*/
//打印输出类
class MyPrint
{
public://重载的函数调用运算符void operator()(string test) {cout << test << endl;}
};
//加法类
class MyAdd {
public:int operator()(int num1, int num2) {return num1 + num2;}
};
void test01() {MyPrint mp;mp("何佳乐");//使用起来非常类似于函数调用,因此称之为函数调用//mp.operator()("何佳乐");
}
void test02() {MyAdd ma;cout << ma(100, 100) << endl;//匿名函数对象 MyAdd()(100, 100),匿名对象执行完当前行就销毁cout << MyAdd()(100, 100) << endl;
}
int main() {//test01();test02();return 0;
}
108 继承
#include<iostream>
using namespace std;
/*继承是面向对象的三大特性之一
*/
class BasePage {
public:void header() {cout << "首页 公开课 登录 注册" << endl;}void footer(){cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl;}void left(){cout << "Java,Python,C++...(公共分类列表)" << endl;}
};
class JAVA :public BasePage {
public:void content() {cout << "this is a java page" << endl;}
};
class CPP :public BasePage {
public:void content() {cout << "this is a c++ page" << endl;}
};
void test01()
{CPP cpp;cpp.header();cpp.footer();cpp.left();cpp.content();JAVA java;java.header();java.footer();java.left();java.content();
}
int main() {test01();return 0;
}
109 **继承方式
#include<iostream>
using namespace std;
/*继承方式1. 公共继承,公共依然公共,保护依然保护,私有无法访问2. 保护继承,公共变成保护,保护依然保护,私有无法访问3. 私有继承,公共变成私有,保护变成私有,私有无法访问
*/class Person
{
public:int num1 = 1;
protected:int num2 = 2;
private:int num3 = 3;
};
class Person1: public Person
{
//public:
// void show() {
// cout << "num1 = " << num1 << endl;
// cout << "num2 = " << num2 << endl;
// //cout << "num3 = " << num3 << endl;
// }
public:Person1() {Person p;num2 = 3;cout << "num2 = " << num2 << endl;//子类成员函数可以访问父类的受保护内容//p.num2 = 4;// 错误:p不是this指针所指的对象,所以不能访问其保护成员}
};
class Person2 :protected Person
{};
class Person3 :private Person
{};
void test01()
{Person1 p1;cout << p1.num1 << endl;//cout << p1.num2 << endl; //错误 : 不在派生类成员函数内,不能访问基类保护成员Person2 p2;//cout << p2.num1 << endl;
}
int main() {test01();return 0;
}
110 **继承中的对象模型
#include<iostream>
using namespace std;
/*继承中的对象模型问题 : 从父类继承过来的成员,哪些属于子类对象首先,c++中,成员变量和成员函数分开存储,并且只有非静态变量才属于类的对象父类中,所有非静态成员属性都会被子类继承下去,不论该成员属性能否被访问到接下来,我们可以利用vs提供的工具,查看Son类的布局1. 找到vs文件夹,或者在开始菜单中找到vs文件夹2. 打开Developer Command Prompt for VS 20193. cd 进入到项目所在的文件夹4. 输入 cl /d1 reportSingleClassLayout类的名称 "42 继承中的对象模型.cpp"例如 : cl /d1 reportSingleClassLayoutSon "42 继承中的对象模型.cpp" 就可以查看son的类结构class Son size(16):+---0 | +--- (base class Base)0 | | m_A4 | | m_B8 | | m_C| +---12 | m_D+---
*/
class Base
{
public:int m_A;
protected:int m_B;
private:int m_C;
};
class Son :public Base {
public:int m_D;
};
void test01()
{Son son;cout << "sizeof(son) = " << sizeof(son) << endl; // 16
}
int main() {test01();return 0;
}
111 继承中构造和析构的顺序
#include<iostream>
using namespace std;
/*继承中,构造和析构的顺序子类继承父类后,当创建子类对象,也会调用父类的构造函数问 : 父类和子类的构造和析构顺序是谁先谁后答 : 先构造父类,再构造子类,先析构子类,再析构父类
*/class Base
{
public:Base() {cout << "父类的构造函数调用" << endl;}~Base() {cout << "父类的析构函数调用" << endl;}
};
class Son :public Base
{
public:Son() {cout << "子类的构造函数调用" << endl;}~Son() {cout << "子类的析构函数调用" << endl;}
};
void test01() {Son son;/*父类的构造函数调用子类的构造函数调用子类的析构函数调用父类的析构函数调用*/
}
int main() {test01();return 0;
}
112 继承时同名成员的处理方式
#include<iostream>
using namespace std;
/*继承中,同名成员的处理方式问 : 当子类与父类出现同名的成员,如何通过子类对象,访问到子类或父类中同名的数据呢?答 : 1. 访问子类同名成员,直接访问即可2. 访问父类同名成员,需要加作用域总结:1. 子类对象可以直接访问到子类中同名成员2. 子类对象加作用域可以访问到父类同名成员3. 当子类与父类拥有同名的成员函数,子类会隐藏父类中同名成员函数,加作用域可以访问到父类中同名函数
*/
class Base {
public:int num1 = 1;void func() {cout << "base-func调用" << endl;}void func(int a) {cout << "base-func(int a)调用" << endl;}
};
class Son :public Base {
public:int num1 = 2;void func() {cout << "son-func调用" << endl;}
};
void test01()
{Son son;cout << "son子类的num1 = " << son.num1 << endl;cout << "父类的num1 = " << son.Base::num1 << endl;
}
void test02() {Son son;son.func();son.Base::func();son.Base::func(10);
}
int main() {//test01();test02();return 0;
}
113 继承时同名静态成员的处理方式
#include<iostream>
using namespace std;
/*继承同名静态成员的处理方式问 : 继承中同名的静态成员在子类对象上如何进行访问静态成员和非静态成员出现同名,处理方式一致- 访问子类同名成员 直接访问即可- 访问父类同名成员 需要加作用域*/
class Base
{
public :static void func() {cout << "Base static void func() " << endl;}static void func(int a) {cout << "Base static void func(int a) " << endl;}static int m_A;
};
int Base::m_A = 100;
class Son :public Base {
public:static void func() {cout << "Son static void func()" << endl;}static int m_A;
};
int Son::m_A = 200;
void test01()
{Son son;cout << "son.m_A = " << son.m_A << endl;cout << "son.Base::m_A = " << son.Base::m_A << endl;cout << "-----------------" << endl;son.func();son.Base::func();son.Base::func(10);
}
void test02() {cout << Son::m_A << endl;cout << Son::Base::m_A << endl;Son::func();Son::Base::func();Son::Base::func(20);
}
int main() {//test01();test02();return 0;
}
114 多继承语法
#include<iostream>
using namespace std;
/*多继承语法c++允许一个类继承多个类1. 语法 : class 子类 : 继承方式 父类1,继承方式 父类2 ,...,继承方式 父类n2. 注意 : 多继承可能引发父类中同名成员出现,需要加作用域区分c++实际开发中,不建议使用多继承
*/
class Base1 {
public:int m_A = 100;int a = 2;
};
class Base2 {
public:int b = 3;int m_A = 200;
};
class Base3 {
public:int c = 4;int m_A = 300;
};
class Son :public Base1, public Base2, public Base3 {
public:int d = 5;int m_A = 400;
};
void test01() {Son son;cout << son.m_A << endl;//400cout << son.Base1::m_A << endl;//100cout << son.Base2::m_A << endl;//200cout << son.Base3::m_A << endl;//300cout << sizeof(son) << endl;}
int main() {test01();return 0;
}
115 菱形继承
#include<iostream>
using namespace std;
/*菱形继承**菱形继承概念:** 两个派生类继承同一个基类 又有某个类同时继承者两个派生类 这种继承被称为菱形继承,或者钻石继承**菱形继承问题:**1. 羊继承了动物的数据,驼同样继承了动物的数据,当草泥马使用数据时,就会产生二义性。2. 草泥马继承自动物的数据继承了两份,其实我们应该清楚,这份数据我们只需要一份就可以。*/
class Animal {
public:int age;
};
/*利用虚继承,可以解决菱形继承的问题Animal就称之为 虚基类
*/
//羊类
class Sheep :virtual public Animal {};
//驼类
class Camal :virtual public Animal {};
//羊驼
class CNM :public Sheep, public Camal {};
void test01() {CNM cnm;cnm.Sheep::age = 18;//报错 : CNM::age 不明确,就是有二义性cnm.Camal::age = 20;//报错 : CNM::age 不明确,就是有二义性cout << "cnm.Sheep::age = " << cnm.Sheep::age << endl;cout << "cnm.Camal::age = " << cnm.Camal::age << endl;cout << "cnm.size is " << sizeof(cnm) << endl; // 8,继承了来自sheep和camal的age各一份,所以是8//但是其实我们有一份就可以了,菱形继承导致这个数据有两份,导致了浪费/*解决后观察对象模型class CNM size(12):+---0 | +--- (base class Sheep)0 | | {vbptr}| +---4 | +--- (base class Camal)4 | | {vbptr}| +---+---+--- (virtual base Animal)8 | age+---CNM::$vbtable@Sheep@:0 | 01 | 8 (CNMd(Sheep+0)Animal)CNM::$vbtable@Camal@:0 | 01 | 4 (CNMd(Camal+0)Animal)vbi: class offset o.vbptr o.vbte fVtorDispAnimal 8 0 4 0解读 :1. {vbptr}代表虚基类指针 v->virtual b->base基类 ptr->pointer该指针指向virtual base table 虚基类表,虚基类表中记录一个偏移量*/
}
int main() { test01();return 0;
}
116 多态
#include<iostream>
using namespace std;
/*多态1. 多态分为两类:1. 静态多态 : 函数重载和运算符重载属于静态多态,复用函数名2. 动态多态 : 派生类和虚函数实现运行时多态2. 静态多态和多态多态的区别1. 静态多态的函数地址早绑定 - 编译阶段确定函数地址2. 动态多态的函数地址晚绑定 - 运行阶段确定函数地址总结:多态满足条件* 有继承关系* 子类重写父类中的虚函数多态使用条件* 父类指针或引用指向子类对象重写:函数返回值类型 函数名 参数列表 完全一致称为重写
*/class Animal {
public://虚函数 : virtual void speak() {cout << "动物在说话" << endl;}
};
class Cat:public Animal {
public:void speak() {cout << "小猫在说话" << endl;}
};
class Dog :public Animal {
public:void speak() {cout << "小狗在说话" << endl;}
};
class A {
public:int num1 = 10;int* p = &num1;
};
class B:public A {};
//地址早绑定,在编译阶段就确定了函数的地址,如果想让猫说话,那么这个函数的地址就不可以早绑定,需要进行动态多态
void doSpeak(Animal& animal) {//Animal& animal = cat;父类引用指向子类对象animal.speak();
}
void test01() {Cat cat;doSpeak(cat);Dog dog;doSpeak(dog);
}
void test02() {cout << sizeof(Animal) << endl; // 4,vfptr虚函数指针 f->function
}
void test03() {int num1 = 10;int* p1 = &num1;int* p2 = p1;cout << (int)p1 << endl;cout << (int)p2 << endl;
}
void test04() {A a;B b;cout << (int)(a.p) << endl;cout << *(a.p) << endl;cout << (int)(b.p) << endl;cout << *b.p << endl;
}
int main() {//test01();//test02();//test03();test04();return 0;
}
117 案例 : 多态计算器
#include<iostream>
using namespace std;
/*多态案例 计算器类案例描述:分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类多态的优点:* 代码组织结构清晰* 可读性强* 利于前期和后期的扩展以及维护
*///普通写法,如果要添加别的计算方式,比如取余之类的,就必须修改源码
class calculator {
public:int num1;int num2;int getResult(string oper) {if (oper == "+"){return num1 + num2;}else if (oper == "-"){return num1 - num2;}else if (oper == "-"){return num1 * num2;}else if (oper == "/" && num2 !=0){return num1 / num2;}else {cout << "请输入正确的运算符" << endl;return -1;}}
};
class AbstractCalculator {
public:int num1;int num2;virtual int getResult() {return 0;}
};
class AddCalculator :public AbstractCalculator{int getResult() {return num1 + num2;}
};
class SubCalculator :public AbstractCalculator {int getResult() {return num1 - num2;}
};
class MulCalculator :public AbstractCalculator {int getResult() {return num1 * num2;}
};
void test01() {calculator calculator;calculator.num1 = 10;calculator.num2 = 11;cout << "num1 + num2 = " << calculator.getResult("+") << endl;
}
void test02() {AbstractCalculator* ac = new AddCalculator;ac->num1 = 10;ac->num2 = 20;cout << ac->getResult() << endl;delete(ac);AbstractCalculator* ac2 = new SubCalculator;ac2->num1 = 10;ac2->num2 = 20;cout << ac2->getResult() << endl;delete(ac2);
}
int main() {//test01();test02();return 0;
}
118 纯虚函数和抽象类
#include<iostream>
using namespace std;
/*纯虚函数和抽象类在多态中,通常父类当中的虚函数的实现是毫无意义的,主要都是调用子类重复书写的内容因此,可以将虚函数改为纯虚函数纯虚函数语法 : virtual 返回值类型 函数名 (参数列表) = 0当类有了纯虚函数,这个类也称之为抽象类抽象类特点 : 1. 无法实例化对象2. 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
*/
class Base {
public:virtual void func() = 0;
};
class Son :public Base {
public:virtual void func() {cout << "son-func() 调用" << endl;}
};
void test01() {//Son son;//报错,son没有重写Base中的纯虚函数Son son;son.func();//Base base;//报错 : 因为有Base有纯虚函数,所以Base是抽象类,抽象类不允许实例化对象Base* base = new Son;base->func();
}
int main() {test01();return 0;
}
119 案例 : 制作饮品
#include<iostream>
using namespace std;
/*多态案例1 : 制作饮品案例描述 : 制作饮品的大致流程为:煮水 - 冲泡 - 倒入杯中 - 加入辅料利用多态技术实现本案例,提供抽象制作饮品基类,提供子类制作咖啡和茶叶
*/
class Drink {
public:virtual void Boil() = 0;virtual void Brew() = 0;virtual void PourInCup() = 0;virtual void PutSomething() = 0;void MakeDrink() {Boil();Brew();PourInCup();PutSomething();}~Drink() {cout << "Drink的析构函数" << endl;}
};
class Tea: public Drink {
public:virtual void Boil() {cout << "煮山泉水" << endl;}virtual void Brew() {cout << "冲洗两遍" << endl;}virtual void PourInCup() {cout << "倒入茶杯" << endl;}virtual void PutSomething() {cout << "加入茶叶" << endl;}~Tea() {cout << "tea的析构函数" << endl;}
};
class Coffee :public Drink {
public:virtual void Boil() {cout << "煮地下水" << endl;}virtual void Brew() {cout << "冲洗" << endl;}virtual void PourInCup() {cout << "倒入咖啡杯" << endl;}virtual void PutSomething() {cout << "加入咖啡豆" << endl;}
};
void doWork(Drink& drink) {drink.MakeDrink();
}
void test01() {Drink* tea = new Tea;tea->MakeDrink();delete(tea);/*Drink* coffee = new Coffee;coffee->MakeDrink();delete(coffee);*/
}
void test02() {Tea tea;doWork(tea);
}
int main() {test01();//test02();return 0;
}
120 虚析构和纯虚析构
#include<iostream>
using namespace std;
/*虚析构和纯虚析构 : 多态使用的时候,如果子类中有属性开辟到堆区,那么父类指针在释放的时候无法调用到子类的析构代码,子类当中的堆区元素就无法释放解决方式 : 将父类中的析构函数改为虚析构或者纯虚析构虚析构和纯虚析构共性 : 1. 可以解决父类指针释放子类对象2. 都需要有具体的函数实现区别 : 1. 如果该类中有纯虚析构,则该类属于抽象类,无法实例化对象总结: 1. 虚析构或纯虚析构就是用来解决通过父类指针释放子类对象 2. 如果子类中没有堆区数据,可以不写为虚析构或纯虚析构 3. 拥有纯虚析构函数的类也属于抽象类*/class Animal {
public:virtual void speak() = 0;Animal() {cout << "Animal的构造函数调用" << endl;}//利用虚析构,可以解决父类指针无法调用子类析构函数的问题/*virtual ~Animal() {cout << "Animal的析构函数调用" << endl;}*///纯虚析构也可以解决上述的问题,这里是纯虚析构的声明,注意,有了纯虚析构函数的类,是抽象类,无法实例化对象virtual ~Animal() = 0;
};
//纯虚析构的定义
Animal::~Animal() {cout << "Animal纯虚析构函数的调用" << endl;
}
class Cat :public Animal {
public:string* m_Name;//堆区Cat(string name) {cout << "CAT构造函数调用" << endl;m_Name = new string(name);}virtual void speak() {cout << *m_Name << "小猫在说话" << endl;}~Cat() {if (m_Name != NULL){cout << "cat析构函数调用" << endl;delete(m_Name);m_Name = NULL;}}};
void test01() {Animal* cat = new Cat("何佳乐");cat->speak();//父类指针在析构的时候,不会调用子类的析构函数,导致如果子类有堆区属性,会出现内存的泄露delete(cat);
}
int main() {test01();return 0;
}
121 文本文件-写文件
#include<iostream>
#include<fstream>
using namespace std;
/*1. 文件操作:概述:程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放通过文件可以将数据持久化c++中对文件操作需要包含头文件<fstream>文件类型分两种:1. 文本文件,文件以文本的ASC2码形式存储在计算机中2. 二进制文件,文件以文本的二进制形式存储在计算机中,用户不能直接读懂操作文件的三大类1. ofstream : 写操作2. ifstream : 读操作3. fstream : 读写操作2. 文本文件(写)步骤 :1. 包含头文件\#include <fstream\>2. 创建流对象ofstream ofs;3. 打开文件ofs.open("文件路径",打开方式);4. 写数据ofs << "写入的数据";5. 关闭文件ofs.close();文件打开方式ios::in为读文件而打开文件ios::out为写文件而打开文件ios::ate初始位置:文件尾ios::app追加方式写文件ios::trunc如果文件存在先删除,再创建ios::binary二进制方式
*/
void test01() {//1. 包含头文件//2. 创建流对象ofstream ofs;//3. 指定打开的方式ofs.open("test.txt", ios::out);//4. 写内容ofs << "姓名:张三" << endl << "年龄:18" << endl << "性别:男" ;//5. 关闭文件ofs.close();
}
int main() {test01();return 0;
}
122 文本文件-读文件
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
/*文本文件 读文件读文件步骤如下:1. 包含头文件\#include <fstream\>2. 创建流对象ifstream ifs;3. 打开文件并判断文件是否打开成功ifs.open("文件路径",打开方式);4. 读数据四种方式读取5. 关闭文件ifs.close();
*/
void test01() {//1. 包含头文件//2. 创建流对象ifstream ifs;//3. 打开文件,并且判断是否打开成功ifs.open("test.txt", ios::in);if (!ifs.is_open()) {cout << "打开文件失败" << endl;return;}//4. 读数据//第一种/*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) {//EOF end of file 文件末尾标志cout << c;}//5. 关闭ifs.close();}
int main() {test01();return 0;
}
123 二进制文件-写文件
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
/*二进制文件 读文件以二进制的方式对文件进行读写操作打开方式指定为 ios::binary写文件概述 : 二进制方式写文件主要利用流对象调用成员函数write函数原型 : ostream& write(const char* buffer,int len);参数解释1. 字符指针buffer指向内存中的一段存储空间2. len是读写的字节数*/
class Person {
public:char m_Name[6];int m_Age;
};
void test01() {//1. 包含头文件//2. 创建流文件ofstream ofs;//3. 打开文件ofs.open("person.txt", ios::out | ios::binary);//4. 写文件Person p = { "好人" , 18 };ofs.write((const char*)&p, sizeof(Person));//5. 关闭ofs.close();
}
int main() {test01();return 0;
}
124 二进制文件-读文件
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
/*二进制文件 读文件二进制方式读文件主要利用流对象调用成员函数read函数原型:istream& read(char *buffer,int len);参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数
*/
class Person {
public:char m_Name[6];int m_Age;
};
void test01() {ifstream ifs;ifs.open("person.txt", ios::in | ios::binary);if (!ifs.is_open()){cout << "打开失败" << endl;return;}//4. 读文件Person p;ifs.read((char*)&p, sizeof(Person));cout << p.m_Name << endl;cout << p.m_Age << endl;ifs.close();
}
int main() {test01();return 0;
}
125 模板
#include<iostream>
using namespace std;
/*模板的概念:模板就是通用的模具,大大提高复用性函数模板1. c++的另一种编程思想称为 泛型编程 ,主要利用的技术就是模板2. c++提供两种模板机制 : 函数模板和类模板函数模板的语法 :1. 函数模板的作用 : 建立一个通用函数,其函数返回值类型和形参类型可以不具体指定,用一个虚拟类型来代表模板语法:template<typename T> //声明一个模板,告诉编译器,后面紧跟着的T不要报错,T是一个通用的数据类型模板使用:利用模板函数有两种方法1. 自动类型推到mySwap(a, b);2. 显示指定类型mySwap<int>(a, b);
*///两个整型交换的函数
void swapInt(int& num1, int& num2)
{int temp = num1;num1 = num2;num2 = temp;
}
//两个浮点型数据交换的函数
void swapDouble(double& a, double& b) {double temp = a;a = b;b = temp;
}
//模板
template<typename T> //声明一个模板,告诉编译器,后面紧跟着的T不要报错,T是一个通用的数据类型
void mySwap(T& num1, T& num2)
{T temp = num1;num1 = num2;num2 = temp;
}
void test01()
{int a = 10;int b = 20;//swapInt(a, b);//利用模板函数有两种方法//1. 自动类型推到//mySwap(a, b);//2. 显示指定类型mySwap<int>(a, b);cout << "a = " << a << endl;cout << "b = " << b << endl;double c = 1.1;double d = 2.2;mySwap(c, d);mySwap<double>(c, d);cout << "c = " << c << endl;cout << "d = " << d << endl;}
int main() {test01();return 0;
}
126 模板注意事项
#include<iostream>
using namespace std;
/*模板注意事项 :1. 自动类型推到,必须推到出一致的数据类型T才可以使用2. 模板必须要确定出T的数据类型才可以使用
*///1.
template<typename T>
void mySwap(T& a, T& b) {T temp = a;a = b;b = temp;
}
void test01()
{int a = 1;int b = 2;char c = 'c';//mySwap(b, c);//报错 : 参数类型为 (int char),无法推到出一致的数据类型
}
template<typename T>
void func() {cout << "func调用" << endl;
}
void test02() {func();//报错 : 没有与参数列表匹配的函数模板func实例,模板必须要确定出T的数据类型才可以使用,即使模板函数没有T也会报错
}
int main() {return 0;
}
127 函数模板案例
#include<iostream>
using namespace std;
/*案例描述:1. 利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序 2. 排序规则从大到小,排序算法为选择排序 3. 分别利用char数组和int数组进行测试
*/
template<typename T>
void mySwap(T& a, T& b)
{T temp = a;a = b;b = temp;
}
template<typename T>
void mySort(T arr[],int len)
{for (int i = 0; i < len; i++){int min = i;for (int j = i + 1; j < len; j++){if (arr[j] < arr[min]){min = j;}}if (min != i){mySwap(arr[min], arr[i]);}}
}
template<typename T>
void printArr(T arr[], int len)
{for (int i = 0; i < len; i++){cout << arr[i] << " ";}cout << endl;
}
void test01()
{//测试char数组char charArr[] = {'b','d','c','f','e','a','g','h'};mySort(charArr, sizeof(charArr)/sizeof(charArr[0]));printArr(charArr, sizeof(charArr) / sizeof(charArr[0]));//测试int数组int intArr[] = { 7, 5, 8, 1, 3, 9, 2, 4, 6 };int num = sizeof(intArr) / sizeof(int); mySort(intArr, num); printArr(intArr, num);
}
int main() {test01();return 0;
}
128 普通函数和函数模板的区别
#include<iostream>
using namespace std;
/*普通函数与函数模板的区别1. 普通函数调用的时候可以发生自动类型转换(隐式类型转换)2. 函数模板调用的时候,如果利用自动类型推到,不会发生隐式类型转换3. 如果利用显示指定类型的方式,可以发生隐式类型转换
*/
int myAdd01(int num1, int num2) {return num1 + num2;
}
template<typename T>
T myAdd02(T num1,T num2) {return num1 + num2;
}
//1. 普通函数调用的时候可以发生自动类型转换(隐式类型转换)
void test01() {int a = 10;int b = 20;char c = 'c';cout << myAdd01(a, c) << endl;
}
//2. 函数模板调用的时候, 如果利用自动类型推到, 不会发生隐式类型转换
void test02() {int num1 = 10;char num2 = 'c';//cout << myAdd02(num1, num2) << endl;// 没有匹配到(int,char)类型,换言之,无法进行自动类型转换
}
//3. 如果利用显示指定类型的方式,可以发生隐式类型转换
void test02() {int num1 = 10;char num2 = 'c';cout << myAdd02<int>(num1, num2) << endl;// 采用显示指定类型的方式,就可以进行自动类型转换
}
int main() {test01();return 0;
}
129 普通函数和模板函数的调用规则
#include<iostream>
using namespace std;
/*普通函数和函数模板的调用规则1. 如果函数模板和普通函数都可以实现,优先调用普通函数2. 可以通过空模板参数列表来强制调用函数模板3. 函数模板也可以发生重载4. 如果函数模板可以更好的产生匹配,优先调用函数模板总结 : 既然提供了函数模板,就最好不要提供普通函数,容易出现二义性
*/
void myPrint(int a, int b) {cout << "调用的普通函数" << endl;
}
template<typename T>
void myPrint(T a, T b) {cout << "调用的函数模板" << endl;
}
template<typename T>
void myPrint(T a, T b, T c) {cout << "调用重载的函数模板" << endl;
}
void test01() {int a = 10;int b = 20;myPrint(a, b);//这个时候,优先调用普通函数//通过空模板参数列表,强制调用函数模板myPrint<>(a,b);//这个时候,强制调用函数模板myPrint(a, b, 100);//即使没有空模板参数列表,这个时候也调用重载的函数模板 char c1 = 'a';char c2 = 'b';myPrint(c1, c2);//调用的函数模板,这里是产生了更好的匹配,因为如果走普通函数,需要进行隐式类型转换,而函数模板不需要
}
int main() {test01();return 0;
}
130 模板的局限性
#include<iostream>
using namespace std;
/*模板的局限性 : 模板的通用性并不是万能的例如 : template<class T>void f(T a, T b){a = b;}如果传入的是一个数组, 就无法实现了因此,c++为了解决这种问题,提供模板的重载,可以为这些特定的类型提供具体化的模板总结 : 1. 利用具体化模板,可以解决自定义类型的通用化2. 学习模板并不是为了写模板,而是在stl能够运用系统提供的模板
*/
class Person {
public:int age;string name;Person(int age,string name) {this->age = age;this->name = name;}//1. 利用运算符重载解决问题/*bool operator==(Person& p2) {if (this->age == p2.age && this->name == p2.name){return true;}else {return false;}}*/
};
template<typename T>
bool myCompare(T& a, T& b) {return a == b;
}
//利用具体化Person的版本实现代码,具体化优先调用
template<> bool myCompare(Person& a, Person& b) {if (a.age == b.age && a.name == b.name){return true;}else {return false;}
}
void test01() {int a = 10;int b = 20;cout << myCompare(a, b) << endl;
}
void test02() {Person p1(18, "Tom");Person p2(18, "Tom");cout << myCompare(p1, p2) << endl;
}
int main() {//test01();test02();return 0;
}
131 类模板
#include<iostream>
using namespace std;
/*类模板类模板与函数模板的区别 :1. 类模板没有自动类型推导的使用方式2. 类模板在模板参数列表中可以有默认参数
*/
template<class NameType, class AgeType = int>//这里就是为AgeType指定了默认参数
class Person {
public:NameType name;AgeType age;Person(NameType name, AgeType age) {this->age = age;this->name = name;}void showPerson() {cout << "name = " << name << endl;cout << "age = " << age << endl;}
};
void test01() {//Person p("zhangsan", 18);//这是错误的,类模板没有自动类型推导 Person<string, int> p("zhangsan", 18);//只可以用显示指定类型p.showPerson();
}
void test02() {Person<string> p("lisi", 20);//因为AgeType有默认参数类型,所以这里可以不用指定,只指定NameTyoe即可p.showPerson();
}
int main() {//test01();test02();return 0;
}
132 类模板中成员函数的创建时机
#include<iostream>
using namespace std;
/*类模板中成员函数的创建时机类模板中成员函数和普通类中的成员函数的创建时机是有区别的1. 普通类中的成员函数一开始就可以创建2. 类模板中的成员函数在调用的时候才可以创建,不调用,哪些成员函数也不存在
*/
class Person1 {
public:void showPerson1() {cout << "Person1 show" << endl;}
};
class Person2 {
public:void showPerson2() {cout << "Person2 show" << endl;}
};
template<class T>
class myClass {
public:T obj;//类模板中的成员函数void fun1() {//在调用的时候,T的类型才会确认,所以fun1和fun2两个成员函数是在调用的时候才创建的obj.showPerson1();}void fun2() {obj.showPerson2();}
};
void test01() {myClass<Person1> m;m.fun1();//m.fun2();
}
int main() {test01();return 0;
}
133 类模板对象做函数参数
#include<iostream>
using namespace std;
/*类模板对象做函数参数学习目标 : 类模板实例化出的对象,向函数传参的方式一共有三种传入的方式1. 指定传入的类型 -- 直接显示对象的数据类型2. 参数模板化 -- 将对象中的参数变为模板进行传递3. 整个类模板化 -- 将这个对象类型模板化进行传递总结 : 在实际开发中,最常用的是指定传入的类型
*/template<class T1,class T2>
class Person {
public:T1 name;T2 age;Person(T1 name, T2 age) {this->age = age;this->name = name;}void showPerson() {cout << "name = " << name << endl;cout << "age = " << age << endl;}
};
//1. 指定传入类型
void printPerson1(Person<string, int>& p) {p.showPerson();
}
//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;
}
//整个类模板化
template<class T>
void printPerson3(T& p) {p.showPerson();cout << "T的数据类型为 : " << typeid(T).name() << endl;
}
void test01() {Person<string, int> p("hejiale", 20);printPerson1(p);printPerson2(p);printPerson3(p);
}
/*name = hejialeage = 20name = hejialeage = 20T1的数据类型为: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >T2的数据类型为: intname = hejialeage = 20T的数据类型为 : class Person<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int>
*/
int main() {test01();return 0;
}
134 类模板与继承
#include<iostream>
using namespace std;
/*类模板与继承当类模板遇到继承的时候,需要注意以下几点1. 当子类继承的父类是一个类模板的时候,子类在声明的时候,要指定出父类中T的类型2. 如果不指定,编译器无法给子类分配内存3. 如果想灵活指定出父类中T的类型,子类也要变为类模板
*/template<class T>
class Base
{
public:T m;
};
//class Son :public Base //错误 : 必须要知道父类中的T类型,才可以继承给子类
class Son :public Base<int>
{};
// 如果想灵活的指定父类中T的类型,那么子类也必须是类模板
template<class T,class T1>
class Son2 :public Base<T>
{T1 obj;char c2;
};
void test01()
{Son s1;s1.m = 20;cout << "s1.m = " << s1.m << endl;
}
void test02()
{Son2<int, char> s2;cout << sizeof(s2) << endl;//为什么占用空间是8个字节?正常的思路应该是int+char+char = 6,因为操作系统会进行对其操作,所以最终占用空间是8
}
int main() {//test01();test02();return 0;
}
135 类模板成员函数类外实现
#include<iostream>
using namespace std;
/*类模板成员函数类外实现学习目标 : 可以掌握类模板中的成员函数类外实现
*/
template<class T1,class T2>
class Person
{
public:T1 name;T2 age;Person(T1 name, T2 age);/*{this->age = age;this->name = name;}*/void showPerson();/*{cout << "age = " << age << endl;cout << "name = " << name << endl;}*/
};
//构造函数的类外实现
template<class T1,class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{this->age = age;this->name = name;
}
//成员函数的类外实现
template<class T1, class T2>
void Person<T1, T2>::showPerson()
{cout << "age = " << age << endl;cout << "name = " << name << endl;
}
int main() {Person<string, int> p("hejiale", 19);p.showPerson();return 0;
}
136 类模板分文件编写
#include<iostream>
#include "person.hpp"
using namespace std;
/*类模板分文件编写学习目标 : 掌握类模板成员函数分文件编写产生的问题以及解决方式问题 : 类模板中成员函数创建时机是在调用阶段,导致分文件编写的时候链接不到解决 : 1. 直接包含.cpp源文件2. 将声明和实现写到一个文件中,并命名为.hpp,hpp是约定的名称,并不是强制
*/
//template<class T1,class T2>
//class Person
//{
//public:
// T1 name;
// T2 age;
// Person(T1 name,T2 age);
// void showPerson();
//};
//template<class T1, class T2>
//Person<T1, T2>::Person(T1 name, T2 age)
//{
// this->age = age;
// this->name = name;
//}
//template<class T1, class T2>
//void Person<T1, T2>::showPerson()
//{
// cout << "age = " << age << endl;
// cout << "name = " << name << endl;
//}
void test01()
{Person<string, int> p("zhangsan", 19);p.showPerson();
}
int main() {test01();return 0;
}
- .hpp
#pragma once
#include <iostream>
using namespace std;template<class T1, class T2>
class Person
{
public:T1 name;T2 age;Person(T1 name, T2 age);void showPerson();
};
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{this->age = age;this->name = name;
}
template<class T1, class T2>
void Person<T1, T2>::showPerson()
{cout << "age = " << age << endl;cout << "name = " << name << endl;
}
137 类模板与友元
#include<iostream>
using namespace std;
/*类模板与友元学习目标 : 掌握类模板配合友元函数的类内和类外实现全局函数类内实现 - 直接在类内声明友元即可全局函数类外实现 - 需要提前让编译器知道全局函数的存在
*/
//2、全局函数配合友元 类外实现 - 先做函数模板声明,下方在做函数模板定义,在做友元
template<class T1, class T2> class Person;//如果声明了函数模板,可以将实现写到后面,否则需要将实现体写到类的前面让编译器提前看到
//template<class T1, class T2> void printPerson2(Person<T1, T2> & p); 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
{//1、全局函数配合友元 类内实现friend void printPerson(Person<T1, T2>& p){cout << "姓名: " << p.m_Name << " 年龄:" << p.m_Age << endl;}//全局函数配合友元 类外实现friend void printPerson2<>(Person<T1, T2>& p);public:Person(T1 name, T2 age){this->m_Name = name;this->m_Age = age;}private:T1 m_Name;T2 m_Age;};//1、全局函数在类内实现
void test01()
{Person <string, int >p("Tom", 20);printPerson(p);
}//2、全局函数在类外实现
void test02()
{Person <string, int >p("Jerry", 30);printPerson2(p);
}int main() {//test01();test02();return 0;
}
138 类模板案例
#include "MyArray.hpp"
/*类模板案例案例描述 : 实现一个通用的数组类,要求如下* 可以对内置数据类型以及自定义数据类型的数据进行存储* 将数组中的数据存储到堆区* 构造函数中可以传入数组的容量* 提供对应的拷贝构造函数以及operator=防止浅拷贝问题* 提供尾插法和尾删法对数组中的数据进行增加和删除* 可以通过下标的方式访问数组中的元素* 可以获取数组中当前元素个数和数组的容量
*/
//测试自定义数据类型
class Person
{
public:string name;int age;Person() {};Person(string name, int age){this->name = name;this->age = age;}
};
void printArray(MyArray<int>& arr)
{for (int i = 0; i < arr.getSize(); i++){cout << arr[i] << endl;}
}
void printArray(MyArray<Person>& arr)
{for (int i = 0; i < arr.getSize(); i++){cout << "姓名 : " << arr[i].name << " || 年龄 : " << arr[i].age << endl;}
}
void test01()
{MyArray<int> arr1(5);for (int i = 0; i < 5; i++){arr1.push_back(i);}cout << "arr1的打印输出 : " << endl;printArray(arr1);cout << "arr的容量 : " << arr1.getCapacity() << endl;cout << "arr的大小 : " << arr1.getSize() << endl;cout << arr1[4] << endl;arr1.pop_back();arr1.pop_back();arr1.pop_back();cout << "arr的容量 : " << arr1.getCapacity() << endl;cout << "arr的大小 : " << arr1.getSize() << endl;printArray(arr1);
}
void test02()
{MyArray<Person> arr(10);Person p1("孙悟空", 999);Person p2("貂蝉", 19);Person p3("赵云", 20);Person p4("韩信", 30);Person p5("李云龙", 44);arr.push_back(p1);arr.push_back(p2);arr.push_back(p3);arr.push_back(p4);arr.push_back(p5);//打印数组printArray(arr);//输出容量cout << arr.getCapacity() << endl;cout << arr.getSize() << endl;}
int main() {//test01();test02();return 0;
}
139 STL
#include<iostream>
using namespace std;
/*STL(standard template library)1. STL的诞生* 长久以来,软件界一直希望建立一种可重复利用的东西* C++的面向对象和泛型编程思想,目的就是复用性的提升* 大多情况下,数据结构和算法都未能有一套标准,导致被迫从事大量重复工作* 为了建立数据结构和算法的一套标准,诞生了STL2. 基本概念* STL(Standard Template Library,**标准模板库**)* STL 从广义上分为: **容器(container) 算法(algorithm) 迭代器(iterator)*** **容器**和**算法**之间通过**迭代器**进行无缝连接。* STL 几乎所有的代码都采用了模板类或者模板函数3. STL六大部件STL大体分为六大组件,分别是:容器、算法、迭代器、仿函数、适配器(配接器)、空间配置器1. 容器:各种数据结构,如vector、list、deque、set、map等,用来存放数据。2. 算法:各种常用的算法,如sort、find、copy、for_each等3. 迭代器:扮演了容器与算法之间的胶合剂。4. 仿函数:行为类似函数,可作为算法的某种策略。5. 适配器:一种用来修饰容器或者仿函数或迭代器接口的东西。6. 空间配置器:负责空间的配置与管理。4. STL中容器、算法、迭代器
*/
int main() {return 0;
}
140 vector容器中存放自定义数据类型
#include<iostream>
#include<vector>
using namespace std;
/*vector容器中存放自定义数据类型
*/
class Person
{
public:string name;int age;Person(string name, int age){this->name = name;this->age = age;}
};
void test01()
{vector<Person> v;Person p1("zhangsan", 18);Person p2("lisi", 28);Person p3("wangwu", 13);Person p4("zhaoli", 20);Person p5("tianqi", 22);//向容器中插入数据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->name << "\t" << "年龄 : " << it->age << endl;}
}
/*存放自定义数据类型指针
*/
void test02()
{vector<Person*> v;Person p1("zhangsan", 18);Person p2("lisi", 28);Person p3("wangwu", 13);Person p4("zhaoli", 20);Person p5("tianqi", 22);//向容器中插入数据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)->name << "\t" << "年龄 : " << (*it)->age << endl;}
}
int main() {//test01();test02();return 0;
}
141 vector容器中嵌套容器
#include<iostream>
#include<vector>
using namespace std;
/*学习目标 : 容器中嵌套容器,外面将对所有数据进行遍历输出
*/
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 it2 = it->begin(); it2 != it->end(); it2++){cout << *it2 << "\t";}cout << endl;}
}
int main() {test01();return 0;
}
142 string构造
#include<iostream>
using namespace std;
/*string的基本概念1. 本质 : string是c++风格的字符串,而string本质上是一个类2. string和char*的区别1. char*是一个指针2. string是一个类,类内部封装了char*,管理zhe'ge字符串,是一个char*的容器3. 特点1. string类内部封装了很多成员方法例如 : 查找find,删除delete,拷贝copy,替换replace,插入insertstring管理char*分配的内存,不用担心复制越界和取值越界等,由类内部进行负责4. 构造函数string() //创建一个空的字符串string(const char* s) //使用字符串s初始化string(const string& str) //使用一个string对象初始化另一个string对象string(int n, char c) //使用n个字符c初始化
*/
void test01()
{//1.string s1; //默认构造//2.const char* str = "hello world";string s2(str);cout << s2 << endl;//3.string s3(s2);cout << s3 << endl;//4.string s4(10, 'a');cout << s4 << endl;
}
int main() {test01();return 0;
}
143 string赋值操作
#include<iostream>
using namespace std;
/*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 << endl;string str2 = str1;cout << str2 << endl;//必须分开写,不能直接等号连接上写string str3;str3 = 'a';cout << str3 << endl;string str4;str4.assign("hello c++");cout << str4 << endl;string str5;str5.assign("hello c++", 6);cout << str5 << endl;string str6;str6.assign(str5);cout << str6 << endl;string str7;str7.assign(10, 'w');cout << str7 << endl;
}
int main() {test01();return 0;
}
144 string拼接
#include<iostream>
using namespace std;
/*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 << endl;str1 += ';';cout << str1 << endl;string str2 = "LOL DNF";str1 += str2;cout << str1 << endl;
}
void test02()
{string str3 = "I";str3.append(" LOVE");cout << str3 << endl;str3.append(" game abcde ", 5);//把" game abcde "的前五个字符拼接到str3的末尾cout << str3 << endl;string str4 = " hejiale";str3.append(str4);cout << str3 << endl; //I LOVE game hejialestring str5 = "LOLDNF";str3.append(str5, 0, 3);//将str5从下标0开始截取三个字符拼接到str5cout << str3 << endl;//I LOVE game hejialeLOLstr3.append(str5, 3, 3);cout << str3 << endl;//I LOVE game hejialeLOLDNF
}
int main() {//test01();test02();return 0;
}
145 string查找和替换
#include<iostream>
using namespace std;
/*string查找和替换**功能描述:*** 查找:查找指定字符串是否存在* 替换:在指定的位置替换字符串**函数原型:*** `int find(const string& str, int pos = 0) const;` //查找str第一次出现位置,从pos开始查找* `int find(const char* s, int pos = 0) const; ` //查找s第一次出现位置,从pos开始查找* `int find(const char* s, int pos, int n) const; ` //从pos位置查找s的前n个字符第一次位置* `int find(const char c, int pos = 0) const; ` //查找字符c第一次出现位置* `int rfind(const string& str, int pos = npos) const;` //查找str最后一次位置,从pos开始查找* `int rfind(const char* s, int pos = npos) const;` //查找s最后一次出现位置,从pos开始查找* `int rfind(const char* s, int pos, int n) const;` //从pos查找s的前n个字符最后一次位置* `int rfind(const char c, int pos = 0) const; ` //查找字符c最后一次出现位置* `string& replace(int pos, int n, const string& str); ` //替换从pos开始n个字符为字符串str* `string& replace(int pos, int n,const char* s); ` //替换从pos开始的n个字符为字符串s
*/
//查找
void test01()
{//findstring str1 = "abcdefgde";cout << str1.find("de") << endl;//3/*rfind 和 find的区别rfind从右往左查找,一般是查找最后出现的位置find从左往右查找*/cout << str1.rfind("de") << endl;//7
}
//替换
void test02()
{string str1 = "abcdefg";//从1号位置起,3个字符,替换为1111str1.replace(1, 3, "1111");cout << str1 << endl;
}
int main() {//test01();test02();return 0;
}
146 string比较
#include<iostream>
using namespace std;
/***功能描述:*** 字符串之间的比较**比较方式:*** 字符串比较是按字符的ASCII码进行对比= 返回 0> 返回 1 < 返回 -1**函数原型:*** `int compare(const string &s) const; ` //与字符串s比较* `int compare(const char *s) const;` //与字符串s比较
*/
void test01()
{string str1 = "aello";string str2 = "hello";cout << str1.compare(str2) << endl;
}
int main() {test01();return 0;
}
147 字符存取
#include<iostream>
using namespace std;
/*string字符存取string中单个字符存取方式有两种* `char& operator[](int n); ` //通过[]方式取字符* `char& at(int n); ` //通过at方法获取字符
*/
void test01()
{string str = "hello";cout << str[0] << endl;cout << str[1] << endl;cout << str[2] << endl;for (int i = 0; i < str.size(); i++){cout << str[i] << " ";}cout << endl;for (int i = 0; i < str.size(); i++){cout << str.at(i) << " ";}cout << endl;//注意 : 这里必须是单引号str[0] = 'x';cout << str << endl;
}
int main() {test01();return 0;
}
148 string插入和删除
#include<iostream>
using namespace std;
/*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个字符
*/
void test01()
{string str = "hello world";//插入str.insert(1, "111");cout << str << endl;// h111ello world//删除str.erase(1, 3);cout << str << endl;
}
int main() {test01();return 0;
}
149 string子串
#include<iostream>
using namespace std;
/*string子串**功能描述:*** 从字符串中获取想要的子串**函数原型:*** `string substr(int pos = 0, int n = npos) const;` //返回由pos开始的n个字符组成的字符串
*/
void test01()
{string str = "abcdef";string substr = str.substr(1, 3);cout << substr << endl;//bcd
}//实用操作
void test02()
{string email = "lisi@sina.com";//从邮箱中获取 用户名信息int pos = email.find("@");string username = email.substr(0, pos);cout << username << endl;
}
int main() {//test01();test02();return 0;
}
150 vector的构造函数
#include<iostream>
#include<vector>
using namespace std;
/*基本概念 :1. 功能 : vector数据结构和数组非常相似,也称为单端数组2. vector和普通数组的区别 : 不同之处在于数组是静态空间,而vector可以动态扩展3. 动态扩展 : 并不是在原空间之后续接新的空间,而是找更大的空间,然后将原数据拷贝新空间,释放原空间4. vector的迭代器是支持随机访问的迭代器vector的构造函数功能描述 : 创建vector容器函数原型 : 1. vector<T> v; //采用模板实现类实现,默认构造函数2. vector(v.begin(), v.end()); //将v[begin(), end())区间中的元素拷贝给本身。3. vector(n, elem); //构造函数将n个elem拷贝给本身。4. vector(const vector &vec); //拷贝构造函数。常用成员方法 : 1. begin 获取指向第一个元素的指针,指针类型是迭代器,下同2. end 获取指向最后一个元素后一个位置的指针3. insert 插入4. rbegin 指向最后一个元素的指针5. rend 指向第一个元素前一个位置的指针
*/
void printVector(vector<int>& v1)
{for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++){cout << *it << " " ;}cout << endl;
}
void test01()
{vector<int> v1;//默认无参构造for (int i = 0; i < 10; i++){v1.push_back(i);}printVector(v1);//2. 通过区间构造vector<int> v2(v1.begin(), v1.end());//[begin,end)前闭后开区间printVector(v2);//3. vector<int> v3(10, 100);//容器中放10个100printVector(v3);//4. 拷贝构造vector<int> v4(v3);printVector(v4);}
int main() {test01();return 0;
}
151 vector赋值操作
#include<iostream>
#include<vector>
using namespace std;
/*vector赋值操作功能描述 : 给vector容器进行赋值函数原型 : 1. vector& operator=(const vector &vec);//重载等号操作符2. assign(beg, end); //将[beg, end)区间中的数据拷贝赋值给本身。3. assign(n, elem); //将n个elem拷贝赋值给本身。
*/
void printVector(vector<int>& v1)
{for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++){cout << *it << " ";}cout << endl;
}
void test01()
{vector<int> v1;for (int i = 0; i < 10; i++){v1.push_back(i);}printVector(v1);//赋值//1.vector<int> v2 = v1;printVector(v2);//2.vector<int> v3;v3.assign(v1.begin(), v1.end());printVector(v3);//3.vector<int> v4;v4.assign(10, 100);//10个100printVector(v4);}
int main() {test01();return 0;
}
152 vector的容量和大小
#include<iostream>
#include<vector>
using namespace std;
/*vector的容量和大小功能描述 : 对vector容器的容量和大小操作函数原型 : 1. empty(); //判断容器是否为空2. capacity(); //容器的容量3. size(); //返回容器中元素的个数4. resize(int num); //重新指定容器的长度为num,若容器变长,则以默认值填充新位置。 //如果容器变短,则末尾超出容器长度的元素被删除。5. resize(int num, elem); //重新指定容器的长度为num,若容器变长,则以elem值填充新位置。 //如果容器变短,则末尾超出容器长度的元素被删除
*/
void test01()
{vector<int> v1;cout << v1.empty() << endl;//1cout << v1.capacity() << endl;//0cout << v1.size() << endl;//0v1.resize(10, 10);cout << v1.empty() << endl;//0cout << v1.capacity() << endl;//10cout << v1.size() << endl;//10v1.push_back(20);cout << v1.capacity() << endl;//15cout << v1.size() << endl;//11v1.push_back(20);v1.push_back(20);v1.push_back(20);v1.push_back(20);v1.push_back(20);cout << v1.capacity() << endl;//22cout << v1.size() << endl;//16v1.resize(2);cout << v1.capacity() << endl;//22cout << v1.size() << endl;//2v1.resize(30);cout << v1.capacity() << endl;//33cout << v1.size() << endl;//30cout << v1[29] << endl;//0
}
int main() {test01();return 0;
}
153 vector插入和删除
#include<iostream>
#include<vector>
using namespace std;
/*vector插入和删除函数原型 : * `push_back(ele);` //尾部插入元素ele* `pop_back();` //删除最后一个元素* `insert(const_iterator pos, ele);` //迭代器指向位置pos插入元素ele* `insert(const_iterator pos, int count,ele);`//迭代器指向位置pos插入count个元素ele* `erase(const_iterator pos);` //删除迭代器指向的元素* `erase(const_iterator start, const_iterator end);`//删除迭代器从start到end之间的元素* `clear();` //删除容器中所有元素
*/
void printVector(vector<int>& v1)
{for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++){cout << *it << " ";}cout << endl;
}
void test01()
{vector<int> v1;//尾插法v1.push_back(1);v1.push_back(2);v1.push_back(3);v1.push_back(4);v1.push_back(5);printVector(v1);//尾删v1.pop_back();v1.pop_back();printVector(v1);//插入 第一个参数是迭代器v1.insert(v1.begin(), 100);printVector(v1);//100 1 2 3v1.insert(v1.begin(), 2, 1000);//在最前面插入2个1000printVector(v1);//1000 1000 100 1 2 3//删除v1.erase(v1.begin());//1000 100 1 2 3printVector(v1);/*删除区间v1.erase(v1.begin(), v1.end());printVector(v1);*/v1.clear();printVector(v1);
}
int main() {test01();return 0;
}
154 vector数据存取
#include<iostream>
#include<vector>
using namespace std;
/*vector数据存取功能描述 : 对vector中的数据的存取操作函数原型 : 1. at(int idx); //返回索引idx所指的数据2. operator[]; //返回索引idx所指的数据3. front(); //返回容器中第一个数据元素4. back(); //返回容器中最后一个数据元素
*/
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] << " ";//0 1 2 3 4 5 6 7 8 9}cout << endl;for (int i = 0; i < v1.size(); i++){cout << v1.at(i) << " ";//0 1 2 3 4 5 6 7 8 9}cout << endl;cout << v1.front() << endl;//0cout << v1.back() << endl; //9
}
int main() {test01();return 0;
}
155 vector互换容器以及内存收缩
#include<iostream>
#include<vector>
using namespace std;
/*vector互换容器以及内存收缩功能描述 : 实现两个容器内元素互换函数原型 : swap(vec) //将vec与本身的元素互换
*/
void printVector(vector<int>& v1)
{for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++){cout << *it << " ";}cout << endl;
}
void test01()
{vector<int> v1;for (int i = 0; i < 10; i++){v1.push_back(i);//0 1 2 3 4 5 6 7 8 9}cout << "交换前 : " << endl;printVector(v1);vector<int> v2;for (int i = 10; i > 0; i--){v2.push_back(i);// 10 9 8 7 6 5 4 3 2 1}printVector(v2);cout << "交换后" << endl;v1.swap(v2);printVector(v1);printVector(v2);
}
//2. 实际用处
//巧用swap可以收缩内存空间
void test02()
{vector<int> v1;for (int i = 0; i < 100000; i++){v1.push_back(i);}cout << v1.capacity() << endl; //138255cout << v1.size() << endl; //100000v1.resize(3);cout << v1.capacity() << endl; //138255cout << v1.size() << endl; //3//我们会发现,v1只存储了三个元素,但是容量确是138255非常大的,容量可以自动扩充,但是无法自动收缩//利用swap,我们可以收缩内存空间vector<int>(v1).swap(v1);/*vector<int>(v1) 利用拷贝构造函数构造了一个匿名对象,*/cout << v1.capacity() << endl; //3cout << v1.size() << endl; //3
}
int main() {//test01();test02();return 0;
}
156 vector预留空间
#include<iostream>
#include<vector>
using namespace std;
/*vector预留空间功能描述 : 减少vector在动态扩展容量时的扩展次数 函数原型 :reserve(int len)//容器预留len个元素长度,预留位置不初始化,元素不可访问,意思就是分配内存了,但是没有初始化无法访问,访问就报错
*/
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);/*首先,我们要知道,容量的改变不是原地改变,而是重新开辟一个内存空间,所以,每次容量改变,容器的地址也会发生改变因此,我们可以利用这个机制,计算出存储100000个数据的时候,会扩容多少次*/if (p != &v[0]){p = &v[0];num++;}}cout << num << endl; // 预留空间前 : 30次,预留空间后 : 1次
}
int main() {test01(); return 0;
}
157 deque容器
#include<iostream>
#include<deque>
using namespace std;
/*deque容器功能 : 双端数组,可以对头端尾端进行插入删除操作deque和vector的区别 : 1. vector对于头部的插入删除效率低下,数据量越大,效率越低2. deque相对而言,对头部的插入删除速度要比vector快3. vector访问元素的速度会比deque快,这和两者内部实现有关常用的类方法 1. push_front2. pop_front3. push_back4. pop_back5. insert6. front7. back8. insert9. begin10. enddeque内部工作原理:deque内部有个**中控器**,维护每段缓冲区中的内容,缓冲区中存放真实数据中控器维护的是每个缓冲区的地址,使得使用deque时像一片连续的内存空间构造函数功能描述 : deque容器构造函数原型:1. deque<T> deqT; //默认构造形式2. deque(beg, end); //构造函数将[beg, end)区间中的元素拷贝给本身。3. deque(n, elem); //构造函数将n个elem拷贝给本身。4. deque(const deque &deq); //拷贝构造函数
*/
void printDeque(deque<int>& d1)
{for (int i = 0; i < d1.size(); i++){cout << d1[i] << " ";}cout << endl;
}
void test01()
{//1.deque<int> d1;for (int i = 0; i < 10; i++){d1.push_back(i);}//2.deque<int> d2(d1.begin(), d1.end());printDeque(d1);printDeque(d2);//3. deque<int> d3(10, 2);printDeque(d3);//4.deque<int> d4(d2);printDeque(d4);
}
int main() {test01();return 0;
}
158 deque赋值操作
#include<iostream>
#include<deque>
using namespace std;
/*deque赋值操作功能描述 : 给deque容器进行赋值函数原型 : 1. deque& operator=(const deque& deq)2. assign(begin,end)3. assign(n,elme)
*/
void printDeque(deque<int>& d1)
{for (int i = 0; i < d1.size(); i++){cout << d1[i] << " ";}cout << endl;
}
void test01()
{deque<int> d1;for (int i = 0; i < 10; i++){d1.push_front(i);}printDeque(d1);//9 8 7 6 5 4 3 2 1 0deque<int> d2 = d1;printDeque(d2);//9 8 7 6 5 4 3 2 1 0deque<int> d3;d3.assign(d1.begin(), d1.end());printDeque(d3);//9 8 7 6 5 4 3 2 1 0d3.assign(10, 2);printDeque(d3);// 2 2 2 2 2 2 2 2 2 2
}
int main() {test01();return 0;
}
159 deque大小操作
#include<iostream>
#include "printDeque.h"
using namespace std;
/*deque大小操作功能描述 : 对deque容器的大小操作函数原型 : 1. deque.empty() //判空2. deque.size() //返回容器中元素个数3. deque.resize(num) //重新指定容器长度,若超出本身长度,补默认值4. deque.resize(num,elem)//重新指定容器长度,若超出本身长度,补elem
*/
void test01()
{deque<int> d1;for (int i = 0; i < 10; i++){d1.push_back(i);}printDeque(d1);cout << d1.empty() << endl;cout << d1.size() << endl;d1.resize(20);printDeque(d1);d1.resize(30, 19);printDeque(d1);/*0 1 2 3 4 5 6 7 8 90100 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 补00 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 19 19 19 19 19 19 19 19 19 19 补19*/
}
int main() {test01();return 0;
}
160 deque插入和删除
#include "printDeque.h"
#include<iostream>
using namespace std;
/*deque插入和删除功能描述 : 向deque容器中插入和删除数据函数原型 : 两端插入操作1. push_back(elem)2. push_front(elem)3. pop_back4. pop_front指定位置操作 -->提供的位置都是迭代器,而不是下标1. insert(pos,elem) //在pos位置插入一个elem元素的拷贝,返回新数据的位置2. insert(pos,n,elem); //在pos位置插入n个elem数据,无返回值。3. insert(pos,beg,end); //在pos位置插入[beg,end)区间的数据,无返回值。4. clear(); //清空容器的所有数据5. erase(beg,end); //删除[beg,end)区间的数据,返回下一个数据的位置。6. erase(pos); //删除pos位置的数据,返回下一个数据的位置。
*/
//两端插入操作
void test01()
{deque<int> d1;for (int i = 0; i < 10; i++){d1.push_front(i);}deque<int> d2;for (int i = 0; i < 10; i++){d2.push_back(i);}printDeque(d1);//9 8 7 6 5 4 3 2 1 0printDeque(d2);//0 1 2 3 4 5 6 7 8 9d1.pop_back();d1.pop_back();printDeque(d1);//9 8 7 6 5 4 3 2d1.pop_front();d1.pop_front();d1.pop_front();printDeque(d1);//6 5 4 3 2
}
//指定位置操作
void test02()
{deque<int> d1;d1.push_back(10);d1.push_back(20);d1.push_back(30);d1.push_back(40);printDeque(d1);deque<int>::iterator it = d1.begin();it++;d1.insert(it, 4);printDeque(d1);//10 4 20 30 40d1.insert(d1.begin(), 2, 1000);printDeque(d1);//1000 1000 10 4 20 30 40deque<int> d2;d2.push_back(1);d2.push_back(2);d2.push_back(3);d2.push_back(4);d2.insert(d2.begin(), d1.begin(), d1.end());printDeque(d2);//1000 1000 10 4 20 30 40 1 2 3 4
}
//删除
void test03()
{deque<int> d1;d1.push_back(10);d1.push_back(20);d1.push_front(100);d1.push_front(200);//200 100 10 20deque<int>::iterator it = d1.begin();it++;d1.erase(it);printDeque(d1);//200 10 20//按区间删除//区间删除d1.erase(d1.begin(), d1.end());printDeque(d1);d1.clear();//清空操作
}
int main() {//test01();//test02();test03();return 0;
}
161 deque数据存取
#include "printDeque.h"
#include<iostream>
using namespace std;
/*deque数据存取- at(int idx); //返回索引idx所指的数据- operator[]; //返回索引idx所指的数据- front(); //返回容器中第一个数据元素- back(); //返回容器中最后一个数据元素
*/
void test01()
{deque<int> d1;d1.push_back(10);d1.push_back(20);d1.push_back(30);d1.push_back(40);cout << d1[0] << endl;//10cout << d1.at(2) << endl;//30cout << d1.front() << endl;//10cout << d1.back() << endl;//40
}
int main() {test01();return 0;
}
162 deque排序
#include "printDeque.h"
#include<iostream>
#include<algorithm>
using namespace std;
/*deque排序算法 : 1. sort(iterator beg, iterator end) //对beg和end区间内元素进行排序注意 : 对于支持随机访问的迭代器的容器,都可以利用sort算法直接对其进行排序,vector也可以利用sort进行排序
*/
void test01()
{deque<int> d1;d1.push_back(1);d1.push_back(4);d1.push_back(2);d1.push_back(3);d1.push_back(8);d1.push_back(6);d1.push_back(0);d1.push_back(7);sort(d1.begin(), d1.end());//默认从小到大printDeque(d1);//0 1 2 3 4 6 7 8
}
int main() {test01();return 0;
}
163 评委打分案例
#include<iostream>
#include<ctime>//和产生真随机数有关的包
#include<vector>
#include<deque>
#include<algorithm>
using namespace std;
/*评委打分案例 : 案例描述 : 有5名选手:选手ABCDE,10个评委分别对每一名选手打分,去除最高分,去除评委中最低分,取平均分。实现步骤 : 1. 创建五名选手,放到vector容器里面2. 遍历vector容器,取出每一个选手,执行for循环,可以把10个评委打分存到deque容器里面3. sort算法对deque容器中分数排序,去除一个最高分和一个最低分4. 遍历deque容器,累加总分,求平均值
*/
class Person
{
public:string name;//姓名int score;//平均分Person(string name, int score){this->name = name;this->score = score;}
};
void createPerson(vector<Person>& v)
{string nameSeed = "ABCDE";for (int i = 0; i < 5; i++){string name = "选手";name += nameSeed[i];Person p(name, 0);//创建选手v.push_back(p);//将选手放入容器}
}
void setScore(vector<Person>& v)
{for (vector<Person>::iterator it = v.begin(); it != v.end(); it++){//将评委的分数,放入deque容器deque<int> d;for (int i = 0; i < 10; i++){int score = rand() % 41 + 60;//60~100的随机数d.push_back(score);}sort(d.begin(), d.end());//排序,方便排序一个最高分和最低分d.pop_back();d.pop_front();//这里就是为什么我们要选用deque,因为deque可以对首尾两端操作,方便我们删除最低分,而vector只可以对尾部操作//求平均分int sum = 0;for (deque<int>::iterator it = d.begin(); it != d.end(); it++){sum += *(it);}int avg = sum / d.size();//将平均分给选手it->score = avg;}
}
void showScore(vector<Person>& v)
{for (vector<Person>::iterator it = v.begin(); it != v.end(); it++){cout << it->name << "\t" << it->score << endl;}
}
int main() {srand((unsigned int)time(NULL));//只有rand的话,产生的是伪随机数,加上这一行代码,可以产生正真意义上的随机数//创建五名选手vector<Person> v;//存放选手的容器createPerson(v);//给选手打分setScore(v);//显示最后得分showScore(v);return 0;
}
164 stack基本概念
#include<iostream>
#include<stack>
using namespace std;
/*stack基本概念 : stack是一种 先进后出 (First In Last Out,FILO)的数据结构,它只有一个出口1. push()入栈2. void pop()出栈3. T top()栈顶元素4. empty()判空5. size()栈的元素个数注意 : 1. 栈不允许有遍历行为,因为我们只可以访问栈的栈顶元素,如果想访问次顶元素,就必须去除栈顶元素,这就破坏了栈的原有结构了,就不是遍历了2. 栈可以判断容器是否为空-->empty()构造函数stack<T> stk; // stack采用模板类实现,stack对象的默认构造形式stack(const stack& stk) // 拷贝构造函数赋值操作运算符重载等号stack& operator=(const stack& stk)数据存取pushvoid pop()top
*/
void test01()
{stack<int> stk;stk.push(1);stk.push(2);stk.push(3);stk.pop();cout << stk.top() << endl;//2stack<int> stk2(stk);cout << stk2.top() << endl; //2 stk2.pop();cout << stk2.top() << endl; //1
}
void test02()
{stack<int> stk;stk.push(1);stk.push(2);stk.push(3);stack<int> stk2 = stk;cout << stk2.top() << endl; //3
}
void test03()
{stack<int> stk;stk.push(1);stk.push(2);stk.push(3);cout << stk.size() << endl;//3cout << stk.empty() << endl;//0
}
void test04()
{stack<int> stk;stk.push(1);stk.push(2);stk.push(3);stk.pop();stk.pop();stk.pop();stk.pop();//会报错,因为stack只有三个元素,pop第四次的时候,stk以及没有数据,所以报错stk.pop();stk.pop();
}
int main() {//test01();//test02();//test03();test04();return 0;
}
165 queue队列
#include<iostream>
#include<queue>
using namespace std;
/*queue队列 : 先进先出的数据结构,有两个出口注意 : 队列中只有队头和队尾可以被外界使用,所以不允许有遍历行为常用接口 : push 入队pop 出队构造函数 : queue<T> que;queue(const queue& que)赋值操作重载等号运算符数据存取pushpopback() 返回最后一个元素front() 返回第一个元素大小操作emptysize();
*/
void test01()
{queue<int> q;q.push(1);q.push(2);q.push(3);cout << "q.size = " << q.size() << endl;//3cout << "q.front = " << q.front() << endl;//1cout << "q.back = " << q.back() << endl;//3cout << "q is empty ? " << q.empty() << endl;//falsewhile (!q.empty()){cout << q.front() << endl;q.pop();}
}
int main() {test01();return 0;
}
166 list容器
#include<iostream>
using namespace std;
/*list容器功能 : 将数据进行链式存储链表 : 是一种物理存储单元上非连续的存储结构,数据元素的逻辑顺序是通过链表中的指针链接实现的组成 : 链表由一系列结点组成结点的组成 : 一个是存储数据元素的数据域,一个是存储下一个结点地址的指针域stl中的链表是一个双向循环链表,指针域由两个指针,分别指向前一个指针和后一个指针,实现双向,并且首元素的前指针域会指向尾元素实现循环优点 : 通过修改指针,方便进行增删元素,不会因为增删元素导致大量的 数据移动 动态存储分配,不会造成内存浪费和溢出缺点 : 不支持随机访问,不可以利用[]访问,遍历的耗费较大由于存在指针域和数据域,所以占用空间比数组大注意 : 1. 由于链表的存储方式并不是连续的空间,一次链表list中的迭代器只支持前移和后移,属于双向迭代器2. List有一个重要的性质,插入操作和删除操作都不会造成原有list迭代器失效(迭代器地址变化,比如vector插入一个元素导致容器满了,这个时候就会重新开辟一个空间,导致迭代器指针改变),这在vector是不成立的3. list的迭代器是双向迭代器,不可以进行跳跃访问,即使 it + 1 也是错误的*/
int main() {return 0;
}
167 ***迭代器失效
#include<iostream>
#include<vector>
#include<deque>
using namespace std;
/*迭代器失效,失效就是迭代器不能用了,不能通过解引用得到数据一、迭代器失效的类型a.由于插入元素,使得容器元素整体“迁移”导致存放原容器元素的空间不再有效,从而使得指向原空间的迭代器失效。b.由于删除元素使得某些元素次序发生变化使得原本指向某元素的迭代器不再指向希望指向的元素。二、vector内部数据结构:数组随机访问每个元素,所需要的时间为O(1)在末尾增加或删除元素所需时间与元素数目无关,在中间或开头增加或删除元素所需时间随元素数目呈线性变化。可动态增加或减少元素,内存管理自动完成,但程序员可以使用reserve()成员函数来管理内存。vector的迭代器在内存重新分配时将失效(它所指向的元素在该操作的前后不再相同)。当把超过capacity()-size()个元素插入vector中时,内存会重新分配,所有的迭代器都将失效;否则,指向当前元素以后的任何元素的迭代器都将失效。当删除元素时,指向被删除元素以后的任何元素的迭代器都将失效。说明:当插入(push_back)一个元素后,end操作返回的迭代器肯定失效。当插入(push_back)一个元素后,capacity返回值与没有插入元素之前相比有改变,则需要重新加载整个容器,此时first和end操作返回的迭代器都会失效。当进行删除操作(erase,pop_back)后,指向删除点的迭代器全部失效;指向删除点后面的元素的迭代器也将全部失效。三、deque内部数据结构:数组随机访问每个元素,所需要的时间为O(1)在开头和末尾增加元素所需时间与元素数目无关,在中间增加或删除元素所需时间随元素数目呈线性变化。可动态增加或减少元素,内存管理自动完成,不提供用于内存管理的成员函数。增加任何元素都将使deque的迭代器失效。在deque的中间删除元素将使迭代器失效。在deque的头或尾删除元素时,只有指向该元素的迭代器失效。说明:在deque容器首部或者尾部插入元素不会使得任何迭代器失效。在其首部或尾部删除元素则只会使指向被删除元素的迭代器失效。在deque容器的任何其他位置的插入和删除操作将使指向该容器元素的所有迭代器失效。四、list内部数据结构:双向环状链表不能随机访问一个元素。可双向遍历。在开头、末尾和中间任何地方增加或删除元素所需时间都为O(1)可动态增加或减少元素,内存管理自动完成。增加任何元素都不会使迭代器失效。删除元素时,除了指向当前被删除元素的迭代器外,其它迭代器都不会失效。说明:插入操作(insert)和接合操作(splice)不会造成原有的list迭代器失效,这在vector中是不成立的,因为vector的插入操作可能造成记忆体重新配置,导致所有的迭代器全部失效。list的删除操作(erase)也只有指向被删除元素的那个迭代器失效,其他迭代器不受影响。(list目前只发现这一种失效的情况)五、slist内部数据结构:单向链表不可双向遍历,只能从前到后地遍历。其它的特性同list相似。六、stack适配器,它可以将任意类型的序列容器转换为一个堆栈,一般使用deque作为支持的序列容器。元素只能后进先出(LIFO)。不能遍历整个stack。七、queue适配器,它可以将任意类型的序列容器转换为一个队列,一般使用deque作为支持的序列容器。元素只能先进先出(FIFO)。不能遍历整个queue。八、priority_queue适配器,它可以将任意类型的序列容器转换为一个优先级队列,一般使用vector作为底层存储方式。只能访问第一个元素,不能遍历整个priority_queue。第一个元素始终是优先级最高的一个元素。九、set键唯一。元素默认按升序排列。如果迭代器所指向的元素被删除,则该迭代器失效。其它任何增加、删除元素的操作都不会使迭代器失效。十、multiset键可以不唯一。其它特点与set相同。十一、map键唯一。元素默认按键的升序排列。如果迭代器所指向的元素被删除,则该迭代器失效。其它任何增加、删除元素的操作都不会使迭代器失效。十二、multimap键可以不唯一。其它特点与map相同。
*/
void test01()
{vector<int> v;v.push_back(1);cout << v.capacity() << endl; //此时的容量为1vector<int>::iterator it = v.begin(); //获得了指向v首元素的迭代器v.push_back(2); //此时的容量为2cout << *it << endl;//这个时候会报错,因为容器的容量发生改变,说明重新开辟了内存空间,所以原来的全部迭代器都失效
}
void test02()
{vector<int> v;v.push_back(1);v.push_back(2);v.push_back(3);v.push_back(4);v.push_back(5);v.push_back(6);v.push_back(7);v.push_back(8);v.push_back(9);v.push_back(10);v.push_back(11);v.push_back(12);v.push_back(13);v.push_back(14);cout << v.capacity() << endl; // 19vector<int>::iterator it = v.begin();for (int i = 0; i < 10; i++){it++;}cout << *it << endl; //11v.erase(it);cout << *it << endl;//这个时候会报错,因为11以及以后元素的迭代器都已经失效了
}
void test03()
{deque<int> d;d.push_back(1);d.push_back(2);d.push_back(3);d.push_back(4);d.push_back(5);d.push_back(6);d.push_back(7);deque<int>::iterator it = d.begin();deque<int>::iterator it2 =d.begin();it2++;//删除前cout << *it << endl;//1cout << *it2 << endl;//2d.pop_front();//cout << *it << endl;//报错,因为迭代器已经失效cout << *it2 << endl;//2it2++;cout << *it2 << endl;//3}
int main() {//test01();//test02();test03();return 0;
}
168 list构造函数
#include<iostream>
#include<list>
#include "MyPrint.h"
using namespace std;
/*list构造函数* `list<T> lst;` //list采用采用模板类实现,对象的默认构造形式:* `list(beg,end);` //构造函数将[beg, end)区间中的元素拷贝给本身。* `list(n,elem);` //构造函数将n个elem拷贝给本身。* `list(const list &lst);` //拷贝构造函数。
*/
void test01()
{list<int> lst;lst.push_back(1);lst.push_back(2);lst.push_back(3);list<int> lst2(lst.begin(), lst.end());cout << lst2.front() << endl; //1list<int> lst3(10, 100);printList(lst3);list<int> lst4 = lst3;printList(lst4);
}
int main() {test01();return 0;
}
169 list赋值和交换
#include<iostream>
#include<list>
#include "MyPrint.h"
using namespace std;
/*list赋值和交换swap可以用来交换
*/
void test01()
{list<int> l1;l1.push_back(10);l1.push_back(20);l1.push_back(30);l1.push_back(40);printList(l1);list<int> l2;l2 = l1;printList(l2);list<int> l3;l3.assign(l2.begin(), l2.end());printList(l3);list<int> l4;l4.assign(10, 100);printList(l4);
}
void test02()
{list<int> l1;l1.push_back(10);l1.push_back(20);l1.push_back(30);l1.push_back(40);list<int> l2;l2.assign(10, 100);cout << "交换前 :" << endl;printList(l1);printList(l2);l1.swap(l2);cout << "交换后 : " << endl;printList(l1);printList(l2);
}
int main() {//test01();test02();return 0;
}
170 list大小操作
#include<iostream>
#include<list>
#include "MyPrint.h"
using namespace std;
/*list大小操作sizeemptyresize(num) 重新指定容器的长度为numresize(num,elem)
*/
void test01()
{list<int> l1;l1.push_back(1);l1.push_back(2);l1.push_back(3);l1.push_back(4);cout << "size = " << l1.size() << endl;cout << "l1 is empty ? " << l1.empty() << endl;l1.resize(10);printList(l1);l1.resize(20, 1000);printList(l1);}
int main() {test01();return 0;
}
171 list插入和删除
#include<iostream>
#include<list>
#include "MyPrint.h"
using namespace std;
/*list插入和删除* push_back(elem);//在容器尾部加入一个元素* pop_back();//删除容器中最后一个元素* push_front(elem);//在容器开头插入一个元素* pop_front();//从容器开头移除第一个元素* insert(pos,elem);//在pos位置插elem元素的拷贝,返回新数据的位置。* insert(pos,n,elem);//在pos位置插入n个elem数据,无返回值。* insert(pos,beg,end);//在pos位置插入[beg,end)区间的数据,无返回值。* clear();//移除容器的所有数据* erase(beg,end);//删除[beg,end)区间的数据,返回下一个数据的位置。* erase(pos);//删除pos位置的数据,返回下一个数据的位置。* remove(elem);//删除容器中所有与elem值匹配的元素。
*/
void test01()
{list<int> l1;l1.push_back(1);//尾插l1.push_back(2);l1.push_back(3);l1.push_front(4);//头插l1.push_front(5);l1.push_front(6);printList(l1);//6 5 4 1 2 3l1.pop_back();l1.pop_front();printList(l1);//5 4 1 2
}
void test02()
{list<int> l1;l1.push_back(1);l1.push_back(2);l1.push_back(3);l1.push_back(4);// 1 2 3 4list<int>::const_iterator it = l1.begin();it++;it++;// it指向3l1.insert(it, 5);//在3前插入5printList(l1);//1 2 5 3 4l1.insert(it, 3, 100);//在3前插入3个100printList(l1);//1 2 5 100 100 100 3 4list<int> l2;l2.push_back(29);l2.push_back(30);l2.push_back(31);l1.insert(it, l2.begin(), l2.end());//在3前插入l2printList(l1);//1 2 5 100 100 100 29 30 31 3 4l1.remove(100);//删除list中的全部100printList(l1);//1 2 5 29 30 31 3 4l1.erase(it, l1.end());//删除3以及之后的数据printList(l1);//1 2 5 29 30 31//cout << *it << endl;// 会报错,因为以及删除了元素3,所以3对应的迭代器已经失效
}
void test03()
{list<int> l1;l1.push_back(1);l1.push_back(2);l1.push_back(3);l1.push_back(4);// 1 2 3 4list<int>::const_iterator it = l1.begin();it++;it++;// it指向3list<int>::const_iterator it2 = l1.erase(it);//删除3,并且返回下一个数据的位置printList(l1);//1 2 4cout << *it2 << endl; // 4l1.clear();//清空lisprintList(l1);
}
int main()
{//test01();//test02();test03();return 0;
}
172 list数据存取
#include<iostream>
#include<list>
#include "MyPrint.h"
using namespace std;
/*list数据存取frontback注意 : 1. list不支持at(0) 访问数据2. list不支持[]访问数据3. list的迭代器是双向迭代器,不可以进行跳跃访问,即使 it + 1 也是错误的,因为根本就没有为双向迭代器进行+的运算符重载
*/
void test01()
{list<int> l1;l1.push_back(1);l1.push_back(2);l1.push_back(3);l1.push_back(4);cout << l1.back() << endl; //4cout << l1.front() << endl; // 1list<int>::const_iterator it = l1.begin();//it = it + 1;}
int main() {test01();return 0;
}
173 list反转和排序
#include<iostream>
#include<list>
#include "MyPrint.h"
using namespace std;
/*list反转和排序 : 将容器中的元素反转,以及将容器中的数据进行排序reverse();sort();sort(MyCompare)
*/
bool myCompare(int num1, int num2)
{//降序 就是第一个数 > 第二个数return num1 > num2;
}
void test01()
{list<int> l1;l1.push_back(1);l1.push_back(5);l1.push_back(2);l1.push_back(3);l1.push_back(16);l1.push_back(7);l1.push_back(4);l1.push_back(8);l1.push_back(12);cout << "反转前 : " << endl;printList(l1);cout << "反转后 : " << endl;l1.reverse();printList(l1);cout << "排序后 : " << endl;/*#include<algorithm>sort(l1,begin(),l1.end())是错误的所有不支持随机访问迭代器的容器,都不可以使用#include<algorithm>的标准算法不支持随机访问迭代器的容器,内部会提供对应的一些算法*/l1.sort(); // 默认排序规则,从小到大printList(l1);/*反转前 :1 5 2 3 16 7 4 8 12反转后 :12 8 4 7 16 3 2 5 1排序后 :1 2 3 4 5 7 8 12 16*/l1.sort(myCompare);printList(l1); //16 12 8 7 5 4 3 2 1
}
int main() {test01();return 0;
}
174 排序案例
#include<iostream>
#include<list>
#include "MyPrint.h"
using namespace std;
/*排序案例 : 案例描述:将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序
*/
class Person
{
public:string name;int age;int height;Person(string name, int age, int height){this->age = age;this->height = height;this->name = name;}
};
bool myCompare(Person& p1, Person& p2)
{if (p1.age == p2.age){return p1.height > p2.height;}else{return p1.age < p2.age;}
}
int main() {Person p1("何佳乐", 18, 191);Person p2("吴超", 22, 181);Person p3("曹越", 14, 183);Person p4("武文强", 22, 175);Person p5("裴要", 14, 173);list<Person> l1;l1.push_back(p1);l1.push_back(p2);l1.push_back(p3);l1.push_back(p4);l1.push_back(p5);l1.sort(myCompare);for (list<Person>::const_iterator it = l1.begin(); it != l1.end(); it++){cout << "name = " << it->name << "\tage = " << it->age << "\theight = " << it->height << endl;}/*name = 曹越 age = 14 height = 183name = 裴要 age = 14 height = 173name = 何佳乐 age = 18 height = 191name = 吴超 age = 22 height = 181name = 武文强 age = 22 height = 175*/return 0;
}
175 set和multiset容器
#include<iostream>
using namespace std;
/*set和multiset容器1. set基本概念 : 所有元素都会在插入的时候自动排序2. 本质 : set/multiset属于关联式容器,底层结构是二叉树实现3. set和multiset区别 : 1. set不允许容器有重复的元素2. multiset允许容器有重复的元素
*/
int main() {return 0;
}
176 set构造和赋值
#include<iostream>
#include<set>
#include "MyPrint.h"
using namespace std;
/*set构造和赋值set<T> st;set(const set& st);赋值 : 重载等号运算符
*/
void test01()
{set<int> s1;s1.insert(10);s1.insert(12);s1.insert(11);s1.insert(9);printSet(s1);//9 10 11 12set<int> s2 = s1;set<int> s3(s1);printSet(s2);//9 10 11 12printSet(s3);//9 10 11 12
}
int main() {test01();return 0;
}
178 set大小和交换
#include<iostream>
#include "MyPrint.h"
using namespace std;
/*set大小和交换sizeemptyswap(st)
*/
void test01()
{set<int> s1;s1.insert(1);s1.insert(2);s1.insert(3);s1.insert(4);cout << "size = " << s1.size() << endl;//4cout << "s1 is empty ? " << s1.empty() << endl;//0set<int> s2;s2.insert(101);s2.insert(102);s2.insert(103);s2.insert(104);printSet(s1);//1 2 3 4printSet(s2);s1.swap(s2);printSet(s1);//101 102 103 104printSet(s2);
}
int main() {test01();return 0;
}
179 set插入和删除
#include<iostream>
#include "MyPrint.h"
using namespace std;
/*set插入和删除* `insert(elem);` //在容器中插入元素。* `clear();` //清除所有元素* `erase(pos);` //删除pos迭代器所指的元素,返回下一个元素的迭代器。* `erase(beg, end);` //删除区间[beg,end)的所有元素 ,返回下一个元素的迭代器。* `erase(elem);` //删除容器中值为elem的元素。
*/
void test01()
{set<int> s1;//插入s1.insert(10);s1.insert(40);s1.insert(30);s1.insert(20);printSet(s1);//删除set<int>::iterator it = s1.begin();it++;set<int>::iterator it2 = s1.erase(it);//删除it指向的20,并返回下一个元素的迭代器printSet(s1);//10 30 40cout << *it2 << endl; //30set<int>::iterator it3 = s1.begin();it3++;s1.erase(it3, s1.end());printSet(s1);//10s1.insert(3);s1.insert(3);//set不允许值重复,所以会只有一个3存入s1.insert(2);s1.insert(5);printSet(s1);//2 3 5 10s1.erase(3);printSet(s1);//2 5 10
}
int main() {test01();return 0;
}
180 set查找和统计
#include<iostream>
#include "MyPrint.h"
using namespace std;
/*set查找和统计 : 对set容器进行查找数据以及统计数据find(key) //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();count(key) //统计key的元素个数(对于set,结果为0或者1)
*/
void test01()
{set<int> s1;s1.insert(1);s1.insert(2);s1.insert(3); s1.insert(4);cout << *s1.find(4) << endl;//4//cout << *s1.find(5) << endl;//报错,end迭代器指针无法解引用cout << "the number of 1 is " << s1.count(1) << endl; //1
}
void test02()
{}
int main() {test01();return 0;
}
181 set和multiset的区别
#include<iostream>
#include "MyPrint.h"
using namespace std;
/*set和multiset的区别1. set不可以有重复值,multiset可以有2. set插入数据的同时会返回pair插入结果,表示插入是否成功,而multiset返回的是迭代器3. multiset不会检测数据,因此可以插入重复数据
*/
void test01()
{set<int> s1;pair < set<int>::iterator, bool> ret = s1.insert(10);if (ret.second){cout << "插入成功" << endl;}else{cout << "插入失败" << endl;}ret = s1.insert(10);if (ret.second){cout << "插入成功" << endl;}else{cout << "插入失败" << endl;}
}
void test02()
{multiset<int> mset;//pair<multiset<int>::iterator, bool> ref = mset.insert(10);//报错,因为multiset返回的是迭代器mset.insert(10);mset.insert(10);mset.insert(10);printMultiset(mset);
}
int main() {//test01();test02();return 0;
}
182 pair对组创建
#include<iostream>
using namespace std;
/*pair对组创建 : 功能描述 : 成对出现的数据,利用对组可以返回两个数据 两种创建方式 : * `pair<type, type> p ( value1, value2 );`* `pair<type, type> p = make_pair( value1, value2 );`
*/
void test01()
{pair<string, int> p("何佳乐", 18);/*注意 : first和second是属性而不是成员函数*/cout << "name = " << p.first << endl;cout << "age = " << p.second << endl;pair<string, int> p2 = make_pair("zhangsan", 22);cout << "name = " << p2.first << endl;cout << "age = " << p2.second << endl;}
int main() {test01();return 0;
}
183 set容器排序
#include<iostream>
#include "MyPrint.h"
using namespace std;
/*set容器排序学习目标 : set容器默认排序规则为从小到大,掌握如何改变排序规则主要技术点 : 利用仿函数,可以改变排序规则vs2019中,仿函数需要加constconst,即括号后面的 const,它的作用是 使得该函数可以被 const 对象所调用对于set存储自定义数据类型,必须要自定义排序规则
*/
class myCompare
{
public:bool operator()(int v1, int v2)const{return v1 > v2;}
};
class Person
{
public:string name;int age;Person(string name, int age){this->age = age;this->name = name;}
};
class comparePerson
{
public:bool operator()(const Person& p1, const Person& p2)const{return p1.age > p2.age;}
};
//利用仿函数可以指针set容器的排序规则
void test01()
{set<int> s1;s1.insert(10);s1.insert(20);s1.insert(50);s1.insert(30);s1.insert(40);printSet(s1);//指定排序规则为从大到小set<int, myCompare> s2;s2.insert(10);s2.insert(20);s2.insert(50);s2.insert(30);s2.insert(40);for (set<int, myCompare>::iterator it = s2.begin(); it != s2.end(); it++){cout << *it << " ";}cout << endl;
}
//自定义数据类型排序
void test02()
{//自定义的数据类型,都会指定排序规则,因为comparePerson是在<>中的,传入的应该是参数类型,所以不用加括号set<Person,comparePerson> s;Person p1("zhangsan", 18);Person p2("lisi", 24);Person p3("zhaosi", 19);Person p4("wangwu", 11);s.insert(p1);s.insert(p2);s.insert(p3);s.insert(p4);for (set<Person>::iterator it = s.begin(); it != s.end(); it++){cout << "name = " << it->name << "\tage = " << it->age << endl;}
}
int main() {//test01();test02();return 0;
}
184 map和multimap容器
#include<iostream>
#include<map>
#include "MyPrint.h"
using namespace std;
/*map和multimap容器1. map基本概念 : 1. 简介 : map中所有元素都是pairpair中第一个元素是key(键值),起到索引作用,第二个值是value(实值)所有元素都会根据元素的键值自动排序2. 本质 : map/multimap属于关联式容器,底层结构是二叉树实现的 3. 优点 : 可以根据key快速找到value4. 和multimap的区别1. map不允许容器中的key重复2. mutlimap允许key重复
*///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));m.insert(pair<int, int>(4, 40));printMap(m);//=重载map<int, int> m2 = m;printMap(m2);//拷贝构造map<int, int> m3(m2);printMap(m3);
}
int main() {test01();return 0;
}
185 map
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*map大小和交换sizeemptyswap(m)map插入(四种插入方式)和删除- `insert(elem);` //在容器中插入元素。- `clear();` //清除所有元素- `erase(pos);` //删除pos迭代器所指的元素,返回下一个元素的迭代器。- `erase(beg, end);` //删除区间[beg,end)的所有元素 ,返回下一个元素的迭代器。- `erase(key);` //删除容器中值为key的元素。map查找和统计- `find(key);` //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回map.end();- `count(key);` //统计key的元素个数,对于map,结果为0/1map容器排序map容器默认排序规则为 按照key值进行 从小到大排序,掌握如何改变排序规则利用仿函数,可以改变排序规则*/
class mycompare
{
public:bool operator()(int v1, int v2)const{return v1 > v2;}
};
class Person
{
public:string name;int age;Person(string name, int age){this->name = name;this->age = age;}
};
class PersonCompare
{
public:bool operator()(const Person& p1, const Person& p2)const{return p1.age > p2.age;}
};
//大小和交换
void test01()
{map<int, int> m;m.insert(pair<int, int>(1, 10));m.insert(pair<int, int>(2, 20));m.insert(pair<int, int>(3, 30));m.insert(pair<int, int>(4, 40));cout << "size = " << m.size() << endl;cout << "map is empty ? = " << m.empty() << endl;map<int, int> m2;m2.insert(pair<int, int>(5, 50));cout << "交换前 : " << endl;printMap(m);printMap(m2);cout << "交换后 : " << endl;m.swap(m2);printMap(m);printMap(m2);
}
//插入和删除
void test02()
{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));//第四种插入方式,不建议用来插入,可以用来访问,访问的时候要确定存在,否则如果不存在,会自动创建value为0的键值对插入m[4] = 40;cout << m[4] << endl;//m.erase(m.begin());//m.erase(m.begin(), m.end());//m.clear();printMap(m);
}
//查找和统计
void test03()
{map<int, int> m;m.insert(pair<int, int>(1, 10));m.insert(pair<int, int>(2, 20));m.insert(pair<int, int>(3, 30));m.insert(pair<int, int>(4, 40));map<int,int>::iterator it = m.find(4); // 注意,查找的是key是否存在,根据key查找cout << it->second << endl;cout << m.count(1) << endl;
}
//map排序
void test04()
{map<int, int, mycompare> m;m.insert(pair<int, int>(1, 10));m.insert(pair<int, int>(2, 20));m.insert(pair<int, int>(3, 30));m.insert(pair<int, int>(4, 40));for (map<int, int>::const_iterator it = m.begin(); it != m.end(); it++){cout << "key = " << it->first << "\tvalue = " << it->second << endl;}map<Person, int, PersonCompare> m2;m2.insert(pair<Person, int>(Person("hejiale", 18), 1));m2.insert(pair<Person, int>(Person("zhangsan", 20), 1));m2.insert(pair<Person, int>(Person("zhaosi", 30), 1));for (map<Person, int>::const_iterator it = m2.begin(); it != m2.end(); it++){cout << "name = " << it->first.name << "\tage = " << it->first.age << "\tvalue = " << it->second << endl;}
}
int main() {//test01();//test02();//test03();test04();return 0;
}
186 案例 - 员工分组
#include<iostream>
#include<ctime>
#include "MyPrint.h"
/*常量的后面不要加分号; !!!!!
*/
#define MEISHU 1
#define CEHUA 2
#define YANFA 3
using namespace std;
/*案例 - 员工分组* 公司今天招聘了10个员工(ABCDEFGHIJ),10名员工进入公司之后,需要指派员工在那个部门工作* 员工信息有: 姓名 工资组成;部门分为:策划、美术、研发* 随机给10名员工分配部门和工资* 通过multimap进行信息的插入 key(部门编号) value(员工)* 分部门显示员工信息
*/
class Employee
{
public:string name;int salary;Employee() {}Employee(string name, int salary){this->name = name;this->salary = salary;}
};
void createEmployeeVector(vector<Employee>& v)
{string name_suffix = "ABCDEFGHIJ";for (int i = 0; i < 10; i++){ Employee e;e.name = "员工";e.name += name_suffix[i];e.salary = 0;v.push_back(e);}
}
void setGroupAndSalary(multimap<int, Employee>& m,vector<Employee>& v)
{//首先,随机分配工资for (vector<Employee>::iterator it = v.begin(); it != v.end(); it++){int salary = rand() % 10000 + 10000; // 100000~19999it->salary = salary;}/*for (vector<Employee>::iterator it = v.begin(); it != v.end(); it++){cout << "name = " << it->name << "\tsalary = " << it->salary << endl;}*///之后,随机分配员工部门for (int i = 0; i < v.size(); i++){int deptId = rand() % 3 + 1; //1~3m.insert(pair<int, Employee>(deptId, v[i]));}
}void showEmployeeInfo(multimap<int, Employee>& m)
{multimap<int, Employee>::iterator it = m.begin();cout << "美术 -- " << m.count(MEISHU) << "人" << endl;if (m.find(MEISHU)!=m.end()){//说明有员工分配到美术部门int count = m.count(MEISHU);for (int i = 0; i < count; i++,it++){cout << "deptId = " << it->first << "\tname = " << it->second.name << "\tsalary = " << it->second.salary << endl;}cout << endl;}cout << "策划 -- " << m.count(CEHUA) << "人" << endl;if (m.find(CEHUA) != m.end()){//说明有员工分配到策划部门int count = m.count(CEHUA);for (int i = 0; i < count; i++, it++){cout << "deptId = " << it->first << "\tname = " << it->second.name << "\tsalary = " << it->second.salary << endl;}cout << endl;}cout << "研发 -- " << m.count(YANFA) << "人" << endl;if (m.find(YANFA) != m.end()){//说明有员工分配到研发部门int count = m.count(YANFA);for (int i = 0; i < count; i++, it++){cout << "deptId = " << it->first << "\tname = " << it->second.name << "\tsalary = " << it->second.salary << endl;}cout << endl;}
}
int main() {srand((unsigned int)time(NULL));vector<Employee> v;multimap<int, Employee> m;//初始化创建10个员工createEmployeeVector(v);//给员工指派部门和工资setGroupAndSalary(m,v);//分部门输出员工消息showEmployeeInfo(m);return 0;
}
187 STL函数对象
#include<iostream>
using namespace std;
/*STL函数对象: 概念 : 1. 重载函数调用操作符()的类,其对象常称之为函数对象2. 函数对象使用重载的()的时候,行为类似于函数调用,所以也叫做仿函数本质 : 函数对象(仿函数)本质是一个类,是一种数据类型,不是一个函数函数对象的使用特点 : 1. 函数对象在使用的时候,可以像普通函数那样子调用,可以有参数,可以有返回值2. 函数对象超出了普通函数的概念,函数对象可以有自己的状态3. 函数对象可以作为参数传递
*/
class myAdd
{
public:int operator()(int num1, int num2){return num1 + num2;}
};
//函数对象在使用的时候,可以像普通函数那样子调用,可以有参数,可以有返回值
void test01()
{myAdd ma;cout << ma(10, 100) << endl;
}
//函数对象超出普通函数的概念,可以有自己的状态
class MyPrint
{
public:void operator()(string test){cout << test << endl;count++;}int count;//内部自己的状态,记录operator()调用次数MyPrint(){this->count = 0;}
};
void test02()
{MyPrint mp;mp("hello world");mp("hello world");mp("hello world");mp("hello world");cout << mp.count << endl;
}
//函数对象可以作为参数传递
void doPrint(MyPrint& mp,string test)
{mp(test);
}
void test03()
{MyPrint mp;doPrint(mp, "c++");
}int main() {//test01();//test02();test03();return 0;
}
188 一元谓词
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*谓词1. 概念 : 返回bool类型的仿函数称之为谓词如果operator接收一个参数,称之为一元谓词,如果接收两个参数,就是两元谓词
*/
class GreaterFive
{
public:bool operator()(int val){return val > 5;}
};
void test01()
{vector<int> v;for (int i = 0; i < 10; i++){v.push_back(i);}//查找容器中大于5的数字/*find_if三个参数1. first2. last ,last和first负责提供区间3. 谓词(pred)GreaterFive()匿名函数对象*/vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());if (it == v.end()){cout << "未找到" << endl;}else{cout << "找到了大于5的数字为 : " << *it << endl;}
}
int main() {test01();return 0;
}
189 二元谓词
#include<iostream>
#include "MyPrint.h"
#include<algorithm>
using namespace std;
/*二元谓词
*/
class myCompare
{
public:bool operator()(int num1, int num2){return num1 > num2;}
};
void test01()
{vector<int> v;v.push_back(1);v.push_back(4);v.push_back(2);v.push_back(3);v.push_back(5);sort(v.begin(), v.end());printVector(v);//使用函数对象 改变算法策略,变排序规则为降序sort(v.begin(),v.end(),myCompare());printVector(v);
}int main() {test01();return 0;
}
190 内建函数对象
#include<iostream>
#include<functional>
using namespace std;
/*内建函数对象1. 概念 : STL内建了一些函数对象2. 分类 : 1. 算术仿函数2. 关系仿函数3. 逻辑仿函数3. 用法 : 1. 这些仿函数产生的对象,用法和一般函数完全相同2. 使用内建函数对象,需要引入头文件 #include<functional>算术仿函数 1. 功能 : 实现四则运算,其中negate是一元运算,其他都是二元运算2. 仿函数原型 : * `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>` //取反仿函数
*/
//negate一元仿函数 取反仿函数
void test01()
{negate<int> n;cout << n(50) << endl;//-50
}//plus二元仿函数 加法仿函数
void test02()
{plus<int> p;cout << p(10, 20) << endl;
}
int main() {//test01();test02();return 0;
}
191 关系仿函数
#include<iostream>
#include<functional>
#include "MyPrint.h"
#include<algorithm>
using namespace std;
/*关系仿函数实现关系对比* `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>` //小于等于
*///大于
void test01()
{vector<int> v;v.push_back(1);v.push_back(3);v.push_back(2);v.push_back(4);v.push_back(5);printVector(v);//想降序sort(v.begin(), v.end(), greater<int>());
}
int main() {test01();return 0;
}
192 逻辑仿函数
#include<iostream>
#include "MyPrint.h"
#include<algorithm>
#include<functional>
using namespace std;
/*逻辑仿函数实现逻辑运算* `template<class T> bool logical_and<T>` //逻辑与* `template<class T> bool logical_or<T>` //逻辑或* `template<class T> bool logical_not<T>` //逻辑非
*/
void test01()
{vector<bool> v;v.push_back(true);v.push_back(false);v.push_back(true);v.push_back(false);printVector(v);//将容器v搬运到v2中,搬运的同时进行取反操作,比如v1的true到v2变成false,这个时候就需要内建函数对象的逻辑仿函数的逻辑非vector<bool> v2;v2.resize(v.size());transform(v.begin(), v.end(), v2.begin(), logical_not<bool>());printVector(v2);
}
int main() {test01();return 0;
}
193 stl常用算法
#include<iostream>
#include "MyPrint.h"
#include<algorithm>
using namespace std;
/*stl常用算法1. 概述* 算法主要是由头文件`<algorithm>` `<functional>` `<numeric>`组成。* `<algorithm>`是所有STL头文件中最大的一个,范围涉及到比较、 交换、查找、遍历操作、复制、修改等等* `<numeric>`体积很小,只包括几个在序列上面进行简单数学运算的模板函数* `<functional>`定义了一些模板类,用以声明函数对象。2. 常用遍历算法for_each 遍历容器transform 搬运容器到另一个容器中3. for_eachfor_each(iterator beg, iterator end, _func); // 遍历算法 遍历容器元素// beg 开始迭代器// end 结束迭代器// _func 函数或者函数对象
*/
void print01(int val)
{cout << val << endl;
}
class print02
{
public:void operator()(int val){cout << val;}
};
void test01()
{vector<int> v;for (int i = 0; i < 10; i++){v.push_back(i);}//这里传入print01是函数指针,函数名就是函数指针,所以不需要也不能加括号for_each(v.begin(), v.end(), print01);for_each(v.begin(), v.end(), print02());}
int main() {test01();return 0;
}
194 transform容器搬运
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*transform容器搬运* transform(iterator beg1, iterator end1, iterator beg2, _func);//beg1 源容器开始迭代器//end1 源容器结束迭代器//beg2 目标容器开始迭代器//_func 函数或者函数对象
*/
class Transfrom
{
public://会自动将容器中的元素作为参数传递给operator,所以这里val实参的类型必须和vector的泛型一致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(), Transfrom());for_each(vTarget.begin(), vTarget.end(), MyPrint());
}
int main() {test01();return 0;
}
195 find
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*- `find` //查找元素- `find_if` //按条件查找元素- `adjacent_find` //查找相邻重复元素- `binary_search` //二分查找法- `count` //统计元素个数- `count_if` //按条件统计元素个数1. find : 查找指定元素,找到返回指定元素的 迭代器,找不到返回结束迭代器end();find(iterator beg, iterator end, value);// 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置// beg 开始迭代器// end 结束迭代器// value 查找的元素注意 : find函数底层会使用==,所以如果是查找自定义数据类型,就必须针对该数据类型重载运算符==
*/class Person
{
public:string name;int age;Person(string name, int age){this->name = name;this->age = age;}bool operator==(const Person& p2){if (this->age == p2.age && this->name == p2.name){return true;}else {return false;}}
};
//查找内置数据类型
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(), 3);if (it == v.end()){cout << "没有找到" << endl;}else{cout << "找到了" << endl;}cout << *it << endl;
}
//查找自定义数据类型
void test02()
{vector<Person> v;v.push_back(Person("hejiale", 20));v.push_back(Person("zhangsan", 11));v.push_back(Person("lisi", 14));v.push_back(Person("wangwu", 22));vector<Person>::iterator it = find(v.begin(), v.end(), Person("hejiale", 20));if (it == v.end()){cout << "没有找到" << endl;}else{cout << "找到了 name = " << it->name << "\tage = " << it->age << endl;}
}
int main() {//test01();test02();return 0;
}
196 find_if
#include<iostream>
#include "MyPrint.h"
#include<algorithm>
using namespace std;
/*find_if : 按条件查找元素find_if(iterator beg, iterator end, _Pred);// 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置// beg 开始迭代器// end 结束迭代器// _Pred 函数或者谓词(返回bool类型的仿函数)
*/class GreaterFive
{
public:bool operator()(int val){return val > 5;}
};
class Person
{
public:string name;int age;Person(string name, int age){this->name = name;this->age = age;}
};
class Greater20
{
public:bool operator()(const Person& p){return p.age > 20;}
};
//内置数据类型
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;}}
//自定义数据类型
void test02()
{vector<Person> v;v.push_back(Person("hejiale", 20));v.push_back(Person("zhangsan", 12));v.push_back(Person("lisi", 29));v.push_back(Person("wangwu", 22));//找年龄大于20的人vector<Person>::iterator it = find_if(v.begin(), v.end(), Greater20());if (it == v.end()){cout << "没有找到" << endl;}else{cout << "找到了 name = " << it->name <<"\tage = " << it->age << endl;}
}
int main() {//test01();test02();return 0;
}
197 adjacent_find
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*adjacent_find : 查找相邻重复元素adjacent_find(iterator beg, iterator end);// 查找相邻重复元素,返回相邻元素的第一个位置的迭代器,没有则返回end// beg 开始迭代器// end 结束迭代器
*/
class Person
{
public:string name;int age;Person(string name, int age){this->name = name;this->age = age;}bool operator==(const Person& p2){if (this->age == p2.age && this->name == p2.name){return true;}else {return false;}}
};
void test01()
{vector<int> v;v.push_back(0);v.push_back(1);v.push_back(1);v.push_back(2);v.push_back(0);v.push_back(3);v.push_back(3);v.push_back(4);vector<int>::iterator it = adjacent_find(v.begin(), v.end());if (it == v.end()){cout << "没有找到" << endl;}else{cout << "找到了" << *it << endl;}
}
void test02()
{vector<Person> v;v.push_back(Person("aaa", 18));v.push_back(Person("aaa", 19));v.push_back(Person("bbb", 18));v.push_back(Person("bbb", 19));v.push_back(Person("bbb", 19));v.push_back(Person("ccc", 18));vector<Person>::iterator it = adjacent_find(v.begin(), v.end());if (it == v.end()){cout << "没有找到" << endl;}else{cout << "找到了 name = " << it->name << "\tage = " << it->age << endl;}
}
int main() {//test01();test02();return 0;
}
198 binary_search
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*binary_search : 利用二分查找的方式,查找指定元素是否存在bool binary_search(iterator beg, iterator end, value);// 查找指定的元素,查到 返回true 否则false// 注意: 在 无序序列 中不可用**// beg 开始迭代器// end 结束迭代器// value 查找的元素
*/
void test01()
{vector<int> v;for (int i = 0; i < 10; i++){v.push_back(i);}//查找容器中是否有9元素bool ref = binary_search(v.begin(), v.end(), 9);cout << ref << endl; // true;
}//如果查找的是无需序列,虽然不会报错,但是将不能保证查找结果的正确
void test02()
{vector<int> v;v.push_back(1);v.push_back(9);v.push_back(5);v.push_back(2);v.push_back(3);bool ref = binary_search(v.begin(), v.end(), 9);cout << ref << endl; // false,返回的结果很明显是错误的
}
int main() {//test01();test02();return 0;
}
199 count
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*count : 统计元素个数int count(iterator beg, iterator end, value); // 统计元素出现次数// beg 开始迭代器// end 结束迭代器// value 统计的元素
*/
class Person
{
public:string name;int age;Person(string name, int age){this->name = name;this->age = age;}bool operator==(const Person& p){if (this->name == name && this->age == age){return true;}else{return false;}}};
//内置数据类型
void test01()
{vector<int> v;v.push_back(10);v.push_back(40);v.push_back(30);v.push_back(40);v.push_back(20);v.push_back(40);cout << count(v.begin(), v.end(), 40) << endl;}
//自定义数据类型
void test02()
{vector<Person> v;v.push_back(Person("hejiale", 20));v.push_back(Person("hejiale", 20));v.push_back(Person("hejiale", 20));v.push_back(Person("hejiale", 20));v.push_back(Person("hejiale", 20));v.push_back(Person("hejiale", 20));v.push_back(Person("hejiale", 20));cout << count(v.begin(), v.end(), Person("hejiale", 20)) << endl;
}
int main() {//test01();test02();return 0;
}
200 count_if
#include<iostream>
#include "MyPrint.h"
#include<algorithm>
using namespace std;
/*count_if : 按条件统计元素个数count_if(iterator beg, iterator end, _Pred);// 按条件统计元素出现次数// beg 开始迭代器// end 结束迭代器// _Pred 谓词
*/
//内置数据类型
class GreaterTwo
{
public:bool operator()(int val){return val > 2;}
};
void test01()
{vector<int> v;v.push_back(1);v.push_back(4);v.push_back(3);v.push_back(2);v.push_back(4);v.push_back(2);cout << count_if(v.begin(), v.end(), GreaterTwo()) << endl;
}
//自定义数据类型
class Person
{
public:string name;int age;Person(string name,int age){this->name = name;this->age = age;}
};
class PersonPred
{
public:bool operator()(const Person& p){if (p.name == "hejiale" && p.age > 14){return true;}return false;}
};
void test02()
{vector<Person> v;v.push_back(Person("hejiale", 18));v.push_back(Person("zhangsan", 20));v.push_back(Person("hejiale", 14));v.push_back(Person("hejiale", 19));v.push_back(Person("hejiale", 14));v.push_back(Person("hejiale", 12));cout << count_if(v.begin(), v.end(), PersonPred()) << endl; // 2
}
int main() {//test01();test02();return 0;
}
201 sort
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
#include<functional>
using namespace std;
/*排序算法 - `sort` //对容器内元素进行排序- `random_shuffle` //洗牌 指定范围内的元素随机调整次序- `merge ` // 容器元素合并,并存储到另一容器中- `reverse` // 反转指定范围的元素sort : 对容器内元素进行排序sort(iterator beg, iterator end, _Pred);// 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置// beg 开始迭代器// end 结束迭代器// _Pred 谓词
*/
void myprint(int val)
{cout << val << " ";
}
//默认排序-升序
void test01()
{vector<int> v;v.push_back(2);v.push_back(3);v.push_back(2);v.push_back(1);v.push_back(3);v.push_back(7);v.push_back(9);v.push_back(4);v.push_back(3);sort(v.begin(),v.end());for_each(v.begin(), v.end(), myprint);
}
class myPred
{
public:bool operator()(int num1, int num2){return num1 > num2;}
};
//降序
void test02()
{vector<int> v;v.push_back(4);v.push_back(3);v.push_back(1);v.push_back(5);v.push_back(7);v.push_back(2);v.push_back(6);//sort(v.begin(), v.end(), myPred());sort(v.begin(), v.end(), greater<int>());for_each(v.begin(), v.end(), myprint);
}
int main() {//test01();test02();return 0;
}
202 random_shuffle
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
#include<ctime>
using namespace std;
/*random_shuffle : 指定范围内的元素随机调整次序`random_shuffle(iterator beg, iterator end); // 指定范围内的元素随机调整次序// beg 开始迭代器// end 结束迭代器
*/
void test01()
{vector<int> v;v.push_back(1);v.push_back(2);v.push_back(3);v.push_back(4);v.push_back(5);v.push_back(6);random_shuffle(v.begin(), v.end());printVector(v);
}
int main() {srand((unsigned int)time(NULL));test01();return 0;
}
203 merge
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*merge : 两个容器元素合并,并存储到另一个容器里面merge(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest); // 容器元素合并,并存储到另一容器中// 注意: 两个容器必须是**有序的** // beg1 容器1开始迭代器// end1 容器1结束迭代器// beg2 容器2开始迭代器// end2 容器2结束迭代器// dest 目标容器开始迭代器注意 : 1. 目标容器需要提前开辟空间2. 合并的两个容器必须是有序的,合并之后的容器也是有序的
*/
void test01()
{vector<int> v1;vector<int> v2;for (int i = 0; i < 10; i++){v1.push_back(i);v2.push_back(i + 10);}// 注意 : 目标容器需要提前开辟空间vector<int> target;target.resize(v1.size() + v2.size());merge(v1.begin(), v1.end(), v2.begin(), v2.end(), target.begin());printVector(target);}
int main() {test01();return 0;
}
204 reverse
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*reverse : 将容器内元素反转reverse(iterator beg, iterator end); // 反转指定范围的元素// beg 开始迭代器// end 结束迭代器
*/
void test01()
{vector<int> v;for (int i = 0; i < 10; i++){v.push_back(i);}reverse(v.begin(), v.end());printVector(v);
}
int main() {test01();return 0;
}
205 copy
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*常用拷贝和替换算法- `copy` // 容器内指定范围的元素拷贝到另一容器中- `replace` // 将容器内指定范围的旧元素修改为新元素- `replace_if ` // 容器内指定范围满足条件的元素替换为新元素- `swap` // 互换两个容器的元素copy : 容器内指定范围的元素拷贝到另一个容器里面copy(iterator beg, iterator end, iterator dest); // 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置// beg 开始迭代器// end 结束迭代器// dest 目标起始迭代器注意 : 目标容器需要提前开辟好空间
*/
void test01()
{vector<int> v;vector<int> target;for (int i = 0; i < 10; i++){v.push_back(i);}target.resize(v.size());copy(v.begin(), v.end(), target.begin());printVector(target);
}
int main() {test01();return 0;
}
206 replace
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*replace : 将容器内指定范围的旧元素修改为新元素replace(iterator beg, iterator end, oldvalue, newvalue); // 将区间内旧元素 替换成 新元素// beg 开始迭代器// end 结束迭代器// oldvalue 旧元素// newvalue 新元素
*/
void test01()
{vector<int> v;v.push_back(1);v.push_back(1);v.push_back(6);v.push_back(3);v.push_back(3);v.push_back(9);v.push_back(2);v.push_back(4);v.push_back(6);v.push_back(3);replace(v.begin(), v.end(), 1, 2);printVector(v);
}
int main() {test01();return 0;
}
207 replace_if
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*replace_if : 将区间内满足条件的元素,替换成指定的元素函数原型 : replace_if(iterator beg, iterator end, _pred, newvalue);// 按条件替换元素,满足条件的替换成指定元素// beg 开始迭代器// end 结束迭代器// _pred 谓词// newvalue 替换的新元素
*/
class Person
{
public:string name;int age;Person(string name, int age){this->name = name;this->age = age;}
};
class myPred
{
public:bool operator()(const Person& p){if (p.name == "hejiale" && p.age == 19){return true;}return false;}
};
void myprint(const Person& p)
{cout << "name = " << p.name << "\tage = " << p.age << endl;
}
void test01()
{vector<Person> v;v.push_back(Person("hejiale", 19));v.push_back(Person("hejiale", 12));v.push_back(Person("zhangsan", 21));v.push_back(Person("lisi", 13));v.push_back(Person("hejiale", 19));replace_if(v.begin(), v.end(), myPred(), Person("HJL", 22));for_each(v.begin(), v.end(), myprint);/*name = HJL age = 22name = hejiale age = 12name = zhangsan age = 21name = lisi age = 13name = HJL age = 22*/
}
int main() {test01();return 0;
}
208 swap
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*swap : 互换两个容器的元素函数原型 : swap(container c1, container c2);// 互换两个容器的元素// c1容器1// c2容器2注意 : swap交换容器的时候,注意交换的容器必须要同种类型
*/
void test01()
{vector<int> v1;vector<int> v2;for (int i = 0; i < 10; i++){v1.push_back(i);v2.push_back(i + 10);}cout << "交换前 : " << endl;printVector(v1);printVector(v2);cout << "交换后 : " << endl;swap(v1, v2);printVector(v1);printVector(v2);}
int main() {test01();return 0;
}
209 accumulate
#include<iostream>
#include"MyPrint.h"
#include<numeric>
using namespace std;
/*常用算术生成算法 : 属于小型算法,使用时包含的头文件为 #include<numeric>算法简介 : 1. accumulate //计算容器内元素累计总和2. fill //向容器内添加元素accumulate : 计算容器内元素累计总和`accumulate(iterator beg, iterator end, value);// 计算容器元素累计总和// beg 开始迭代器// end 结束迭代器// value 起始值
*/
void test01()
{vector<int> v;for (int i = 1; i <= 10; i++){v.push_back(i);}cout << accumulate(v.begin(), v.end(), 0) << endl;}
int main() {test01();return 0;
}
210 fill
#include<iostream>
#include<numeric>
#include "MyPrint.h"
using namespace std;
/*fill : 向容器中填充指定元素`fill(iterator beg, iterator end, value);// 向容器中填充元素// beg 开始迭代器// end 结束迭代器// value 填充的值总结 : 利用fill可以将容器区间内元素填充为 指定的值
*/
void test01()
{vector<int> v;v.resize(20);// 记得提前开辟空间fill(v.begin(), v.end(), 10);printVector(v);
}
int main() {test01();return 0;
}
211 set_intersection
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*常用集合算法 : - `set_intersection` // 求两个容器的交集- `set_union` // 求两个容器的并集- `set_difference ` // 求两个容器的差集set_intersection : 求两个容器交集iterator set_intersection(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);// 求两个集合的交集// **注意:两个集合必须是有序序列**// beg1 容器1开始迭代器// end1 容器1结束迭代器// beg2 容器2开始迭代器// end2 容器2结束迭代器// dest 目标容器开始迭代器总结 : 1. 求交集的两个集合必须的有序序列2. 目标容器开辟空间需要从**两个容器中取小值**3. set_intersection返回值既是交集中最后一个元素的位置
*/
void myprint(int val)
{cout << val << " ";
}
void test01()
{vector<int> v;v.push_back(1);v.push_back(1);v.push_back(6);v.push_back(10);v.push_back(13);v.push_back(19);v.push_back(22);v.push_back(24);v.push_back(26);v.push_back(33);vector<int> v2;v2.push_back(1);v2.push_back(7);v2.push_back(8);v2.push_back(13);v2.push_back(15);v2.push_back(17);v2.push_back(21);v2.push_back(23);v2.push_back(30);v2.push_back(33);v2.push_back(34);vector<int> target;target.resize(min(v.size(), v2.size()));vector<int>::iterator it = set_intersection(v.begin(), v.end(), v2.begin(), v2.end(), target.begin());for_each(target.begin(), it, myprint);cout << endl;
}
int main() {test01();return 0;
}
212 set_union
#include<iostream>
#include "MyPrint.h"
#include<algorithm>
using namespace std;
/*set_union : 求两个集合的并集set_union(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest); // 求两个集合的并集// **注意:两个集合必须是有序序列**// beg1 容器1开始迭代器// end1 容器1结束迭代器// beg2 容器2开始迭代器// end2 容器2结束迭代器// dest 目标容器开始迭代器注意 : - 求并集的两个集合必须是有序序列- 目标容器开辟空间需要**两个容器相加**- set_union返回值既是并集中最后一个元素的位置
*/
void myprint(int val)
{cout << val << " ";
}
void test01()
{vector<int> v;v.push_back(1);v.push_back(1);v.push_back(6);v.push_back(10);v.push_back(13);v.push_back(19);v.push_back(22);v.push_back(24);v.push_back(26);v.push_back(33);vector<int> v2;v2.push_back(1);v2.push_back(7);v2.push_back(8);v2.push_back(13);v2.push_back(15);v2.push_back(17);v2.push_back(21);v2.push_back(23);v2.push_back(30);v2.push_back(33);v2.push_back(34);vector<int> target;target.resize(v.size() + v2.size());vector<int>::iterator it = set_union(v.begin(), v.end(), v2.begin(), v2.end(), target.begin());for_each(target.begin(), it, myprint);
}
int main() {test01();return 0;
}
213 set_difference
#include<iostream>
#include<algorithm>
#include "MyPrint.h"
using namespace std;
/*set_difference : 求两个集合的差集set_difference(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);// 求两个集合的差集// **注意:两个集合必须是有序序列**// beg1 容器1开始迭代器// end1 容器1结束迭代器// beg2 容器2开始迭代器// end2 容器2结束迭代器// dest 目标容器开始迭代器注意 : - 求差集的两个集合必须的有序序列- 目标容器开辟空间需要从**两个容器取较大值**- set_difference返回值既是差集中最后一个元素的位置
*/
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);}printVector(v1);printVector(v2);vector<int> vTarget;//取两个里面较大的值给目标容器开辟空间vTarget.resize(max(v1.size(), v2.size()));//返回目标容器的最后一个元素的迭代器地址cout << "v1与v2的差集为: " << endl;vector<int>::iterator itEnd =set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());for_each(vTarget.begin(), itEnd, myPrint());cout << endl;cout << "v2与v1的差集为: " << 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();return 0;
}
自己学习c++过程中写下的笔记,只做基础了解使用相关推荐
- 学习编程过程中-->遇到的错误
文章目录 学习编程过程中-->遇到的错误(吕招焕) 1.java.sql.SQLException: Parameter index out of range (2 > number of ...
- 机器深度学习的过程中盛传着7 个误解,我们来一一揭开
https://www.toutiao.com/a6690402605824213508/ 2019-05-13 14:59:45 哥伦比亚大学计算机科学专业博士生Oscar Chang发博阐述了关於 ...
- 学习Java过程中那些知道名字却不理解含义的大集合
每次和其他人讨论的时候总会出现,别人说一个术语或者一个英文简称我总是一脸懵逼,脑袋里的想法就是:听过很多次这个词,但就是不理解是什么意思.所以总结了一下我遇到的一些词,并查询了一些资料终于把它们弄懂了 ...
- 【Word文档修改过程中空格下划线打印不出来问题解决】
Word文档修改过程中空格下划线打印不出来问题解决
- 在学习EasyX过程中,遇到“没有与参数列表匹配的重载函数loadimage”,修改解决方案字符集属性无效后的解决方法
在学习EasyX过程中,遇到"没有与参数列表匹配的重载函数loadimage"的问题,在网上查询后,很多人给出的方法是--修改解决方案字符集属性. 解决"E0304&qu ...
- 利用JQ实现的,高仿 彩虹岛官网导航栏(学习HTML过程中的小记录)
利用JQ实现的,高仿 彩虹岛官网导航栏(学习HTML过程中的小记录) 作者:王可利(Star·星星) 总结: 今天学习的jQ类库的使用,代码重复的比较多需要完善.严格区分大小写,在 $(" ...
- vscode中写markdown格式笔记的配置过程和相关语法
vscode中写markdown格式笔记的配置过程和相关语法 一.引言 二.安装相关插件 三.开始使用vscode进行编写 四.相关语法 参考链接: link link 一.引言 以前使用 Typor ...
- oracle集群+默认什么组,Oracle RAC 建设过程中必须应知、应做(上)
原标题:Oracle RAC 建设过程中必须应知.应做(上) 作者:赵海,某城商行系统架构师,专注并擅长银行数据中心解决方案规划及设计.目前在社区会员关注TOP100排行榜中名列第三位,社区专业技能榜 ...
- Django大咖之路: 如何对付学习Django过程中所遇到的挫败感?
Django作为一个成熟的网站和网络应用开发框架,有着大而全的模块和功能.对于刚从事网站开发或刚熟悉Python语言的新手而言,觉得学习Django好难是一件非常普遍的事情.小编我就以亲身经历告诉你如 ...
最新文章
- Oracle RAC 客户端连接负载均衡(Load Balance)
- where used list repository table WBCROSSGT
- SharePoint 2013让页面显示错误
- Ajax同步链接在IE 与FireFox的使用差别 open(GET,url,false)
- 临危不惧和力记易让容灾也有真本事
- Python 各种库下载地址介绍
- JTAG接口针脚定义及含义
- Sigmoid函数总结
- Multisim 安装、破解、汉化、卸载教程
- PHP调用京东联盟接口以及配置签名
- 没有任何借口——提升职场能力的文章
- DataGrip使用技巧
- IDEA download sources 报Cannot reconnect错误解决方法
- T00ls Lpk Sethc 全新v2.0版(附LPK提权)
- 基于python的阴阳师后台辅助
- ArcEngine添加指北针
- matlab_颜色矩阵三原色
- php2twig,php twig是什么意思
- UnityC#接阿里云头像自动分割API
- Cypress系列(50)- wrap() 命令详解
热门文章
- java future 异常处理_Java异常处理总结
- 大疆软件经纬度偏差消除
- 2017高校计算机挑战赛,中国高校计算机大赛-网络技术挑战赛竞赛规程(2017年.PDF...
- 优惠券运营指南:一张搞定拉新、促活、转化、召回
- 指向数组的指针的理解
- 文章本天成|跟我一起来一场简洁易懂的servlet的过滤器Filter的学习吧
- 码分多址(CDMA)的本质-正交之美
- python怎么加油_使用 Python 为你的油箱加油
- 数据表的字段约束:主键、外键、唯一
- razer鼠标测试软件,那伽梵蛇2014版鼠标驱动及测试_雷蛇鼠标_键鼠评测-中关村在线...