C++提高编程
1.STL初识
1.1 STL的诞生
- 长久以来,软件界一直希望建立—种可重复利用的东西
- C++的面向对象和泛型编程思想,目的就是复用性的提升
- 大多情况下,数据结构和算法都未能有一套标准,导致被迫从事大量重复工作
- 为了建立数据结构和算法的—套标准,诞生了STL
1.2 STL基本概念
- STL(Standard Template Library,标准模板库)
- STL从广义上分为:容器(container)算法(algorithm)迭代器(iterator)
- 容器和算法之间通过迭代器进行无缝连接。
- STL几乎所有的代码都采用了模板类或者模板函数
1.3 STL六大组件
STL大体分为六大组件,分别是:容器、算法、迭代器、仿函数、适配器(配接器)、空间配置器
1.容器:各种数据结构,如vector、list、deque、set、map等,用来存放数据。
2.算法:各种常用的算法,如sort、find、copy、for_each等
3.迭代器:扮演了容器与算法之间的胶合剂。
4.仿函数:行为类似函数,可作为算法的某种策略。
5.适配器:—种用来修饰容器或者仿函数或迭代器接口的东西。
6.空间配置器:负责空间的配置与管理。
1.4 STL中容器、算法、迭代器
容器:置物之所也
STL容器就是将运用最广泛的—些数据结构实现出来
常用的数据结构:数组,链表,树,栈,队列,集合,映射表等
这些容器分为序列式容器和关联式容器两种:
- **序列式容器:**强调值的排序,序列式容器中的每个元素均有固定的位置。
- 关联式容器:二叉树结构,各元素之间没有严格的物理上的顺序关系
算法:问题之解法也 algorithm
有限的步骤,解决逻辑或数学上的问题,这一门学科我们叫做算法(Algorithms)
算法分为:质变算法和非质变算法。
- 质变算法:是指运算过程中会更改区间内的元素的内容。例如拷贝,替换,删除等等
- 非质变算法:是指运算过程中不会更改区间内的元素内容,例如查找、计数、遍历、寻找极值等等
迭代器:容器和算法之间粘合剂
提供一种方法,使之能够依序寻访某个容器所含的各元素耐无需暴露该容器的内部表示方式。
每个容器都有自己专属的迭代器
迭代器使用非常类似于指针,初学阶段我们可以先理解迭代器为指针
迭代器种类: | 功能 | 支持运算 |
---|---|---|
输入迭代器 | 对数据的只读访问 | 只读,支持++、==、!= |
输出迭代器 | 对数据的只写访问 | 只写,支持++ |
前向迭代器 | 读写操作,并能向前推进迭代器 | 写,支持++、==、!= |
双向迭代器 | 读写操作,并能向前和向后操作 | 读写,支持++、- |
随机访问迭 | 读写操作,可以以跳跃的方式访问任意数据,功能最强的迭代器 | 读写,持++、–、[n] -n、<、<=、>、>= |
常用的容器中迭代器种类为双向迭代器,和随机访问迭代器。
1.5容器算法迭代器初识
了解 ST L中容器、算法、迭代器概念之后,我们利用代码感受STL的魅力
ST L中最常用的容器为Vector.可以理解为数组,下面我们将学习如何向这个容器中插入数据、 并遍历这个容器。
1.5.1 Vector 存放内置数据类型
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myPrint(int val)
{
}
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
//通过迭代器访问数组中的数据
vector<int>::iterator itBegin=v.begin();
vector<int>::iterator itEnd=v.end();
//第一种遍历方式
while(itBegin!=itEnd)
{
cout<<*itBegin<<endl;
itBegin++;
}
//第二种遍历方式
for(vector<int>::itaretor it=v.begin();it!=v.end();it++)
{
cout<<*it;
}
//第三种遍历方式
for_each(v.begin(),v.end(),myPrint);
}
1.5.2 Vector存放自定义数据类型
#include<iostream>
#include<string>
#include<vector>
#include<string>
using namespace std;
//vector 容器中存放自定义数据类型
class Person {
public:
Person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void test01()
{
vector<Person>v;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
Person p5("eee", 50);
//向容器中添加数据
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
//遍历容器中的数据
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名:" << (*it).m_name ;
cout << " 年龄:" << it->m_age<< endl;
}
}
//存放自定义数据类型的指针
void test02()
{
vector<Person*>v;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
Person p5("eee", 50);
//向容器中添加数据
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
v.push_back(&p5);
for (vector<Person*>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名:" << (*it)->m_name;
cout << " 年龄:" << (*it)->m_age << endl;
}
}
int main()
{
test02();
system("pause");
return 0;
}
1.5.3 Vector容器嵌套容器
#include<iostream>
#include<string>
#include<vector>
#include<string>
using namespace std;
//容器嵌套容器
void test02()
{
vector<vector<int>>v;
//创建小容器、
vector<int>v1;
vector<int>v2;
vector<int>v3;
vector<int>v4;
//向小容器中添加数据
for (int i = 0; i < 4; i++)
{
v1.push_back(i + 1);
v2.push_back(i + 2);
v3.push_back(i + 3);
v4.push_back(i + 4);
}
//将小容器添加到大容器中
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
v.push_back(v4);
for (vector<vector<int>>::iterator it = v.begin(); it != v.end(); it++)
{
//(*it)------容器 vector<int>
for (vector<int>::iterator vit = (*it).begin(); vit != (*it).end(); vit++)
{
cout << *vit << " ";
}
cout << endl;
}
}
int main()
{
test02();
system("pause");
return 0;
}
2. STL常用容器
2.1 String容器
2.1.1 string基本概念
本质:
- string是C+ +风格的字符串,而string本质上是一 个类
string和char *区别:
- char*是一个指针
- string是一 个类,类内部封装了char,管理这个字符串,是一个char*的容器。
特点:
string类内部封装了很多成员方法
例如:查找find, 拷贝copy,删除delete 替换replace,插入insert
string管理char*所分配的内存,不用担心复制越界和取值越界等,由类内部进行负责
2.1.2 string构造函数
构造函数原型:
#include<iostream>
#include<string>
using namespace std;
//string 的构造函数
/*
string(); //创建一个空的字符串 例如: string str;
string(const char* s); //使用字符串s初始化
string(const stping& str); //使用- -个string对象初始化另一个string对象
string(int n, char c); //使用n个字符c初始化
*/
void test01()
{
string s1;
const char* str = "fdsf";
string s2(str);
cout << "s2=" << s2 << endl;
string s3(s2);
cout << "s3=" << s3 << endl;
string s4(10, 'a');
cout << "s4=" << s4 << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
2.1.3 string 赋值操作
#include<iostream>
#include<string>
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 = "dfsdfg";
cout << "str1=" << str1 << endl;
string str2;
str2 = str1;
cout << "str2=" << str2 << endl;
string str3 = "a";
cout << "str3=" << str3 << endl;
string str4;
str4.assign("defsdf");
cout << "str4=" << str4 << endl;
string str5;
str5.assign("fdsfdgdfg", 5);
cout << "str5=" << str5 << endl;
string str6;
str6.assign(str4);
cout << "str6=" << str6 << endl;
string str7;
str7.assign(10,'q');
cout << "str7=" << str7 << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
2.1.4 string字符串拼接
功能描述:实现在字符串末尾拼接字符串
#include<iostream>
#include<string>
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="dfsdfg";
str1 += "qqqq";
cout << "str1=" << str1 << endl;
string str2="qqqq";
str2 += "c";
cout << "str2=" << str2 << endl;
string str3 = "sdfdgg";
str3 += str2;
cout << "str3=" << str3 << endl;
string str4="wo";
str4.append("defsdf",3);
str4.append(str2);
str4.append(str2, 2, 4);
cout << "str4=" << str4 << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
2.1.5 string 查找和替换
功能描述:
●查找:查找指定字符串是否存在
●替换:在指定的位置替换字符串
#include<iostream>
#include<string>
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 chan* s);//替换从pos开始的n个字符为字符串s
*/
//1.查找
void test01()
{
string str1 = "abcdefg";
//find
int position=str1.find("df");
if (position == -1)
{
cout << "未找到字符串" << endl;
}
else
{
cout << "找到字符串" << endl;
}
//rfind
position = str1.rfind("de");
cout << position << endl;
//rfind 从右往左查
//find 从左往右查
}
//---------------替换-------------
void test02()
{
string str1 = "abcdefg";
//从1号字符起 3个字符 替换为1111
str1.replace(1, 3, "1111"); //输出 a1111efg
cout << str1 << endl;
}
int main()
{
test07();
system("pause");
return 0;
}
总结:
- find查找是从左往后,rfind从右往左
- find找到字符串后返回查找的第一个字符位置 ,找不到返回-1
- replace在替换时,要指定从哪个位置起,多少个字符,替换成什么样的字符串
2.1.6 string字符串比较
功能描述:
●字符串之间的比较
比较方式:
●字符串比较是按字符的ASCII码进行对比
=返回 0
>返回 1
<返回 -1
//string 字符串比较 按字符的ascII码值进行比较
/*
函数原型:
int compare(const string &s) const; //与字符串s比较
int compare(const char *s) const;//与字符串s比较
*/
void test03()
{
string str1 = "zwer";
string str2 = "qwer";
if (str1.compare(str2) == 0)
{
cout << "str1=str2" << endl;
}
else if(str1.compare(str2) >0)
{
cout << "str1>str2" << endl;
}
else
{
cout << "str1<str2" << endl;
}
}
2.1.7 string字符存取
string中单个字符存取方式有两种
//字符串存取
// char& operator[](int n) 通过[]方式存取字符
// char& at(int n) 通过at方法获取字符
void test04()
{
string str1 = "Hello";
//cout << "str1="<<str1 << endl;
//通过[]访问字符
for (int i = 0; i < str1.size(); i++)
{
cout << str1[i] << " ";
}
cout << endl;
//通过at访问字符
for (int i = 0; i < str1.size(); i++)
{
cout << str1.at(i) << " ";
}
cout << endl;
//修改单个字符
str1[0] = 'x';
cout << "str1=" << str1 << endl;
str1.at(1) = 'x';
cout << "str1=" << str1 << endl;
}
2.1.8 string插入和删除
功能描述:
对string字符串进行插入和删除字符操作
//string 插入和删除 其起始下标都是0
/*
string& insert(int pos ,const char* s);//插入字符串
string& insert(int pos, const string& str);//插入字符串
string& insert(int pos, int n, char c);/l在指定位置插入n个字符c
string& erase(int pos, int n = npos);//删除从Pos开始的n个字符
*/
void test05()
{
string str1 = "hello";
//插入
str1.insert(1, "1111");
cout << "str1=" << str1 << endl;
//删除 从哪个位置起删掉几个字符
str1.erase(1, 4);
cout << "str1=" << str1 << endl;
}
2.1.9 string子串
//string 子串
//string substr(int pos=0,int n=npos)const 返回由pos开始的n个字符组成的字符串
void test06()
{
string str = "abcdefg";
string substr=str.substr(1, 3);
cout << "substr="<< substr << endl;
}
void test07()
{
string email = "hello@sina.com";
//从邮件地址中获取 用户名信息
int pos = email.find("@");
string name = email.substr(0, pos);
cout << "name=" << name << endl;
}
2.2 Vector容器
2.2.1 vector基本概念
功能:
- vector数据结构和数组非常相似,也称为单端数组
vector与普通数组区别:
- 不同之处在于数组是静态空间,而vector可以动态扩展
动态扩展:
- 并不是在原空间之后续接新空间,而是找更大的内存空间,然后将原数据拷贝新空间,释放原空间
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2dIFDvaU-1602228009277)(C:\Users\leovo\AppData\Roaming\Typora\typora-user-images\image-20201007100846151.png)]
- Vector容器的迭代器是支持随机访问的迭代器
2.2.2 vector的构造函数
#include<iostream>
#include<string>
#include <vector>
using namespace std;
//打印函数
void printVector(vector<int>& v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
//vector 构造函数
void test01()
{
vector<int>v1;//默认构造
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
printVector(v1);
//通过区间方式构造
vector<int>v2(v1.begin(), v1.end());
printVector(v2);
//n个elem 方式构造
vector<int>v3(10, 100);
printVector(v3);// 打印10个100
//拷贝构造*
vector<int>v4(v3);
printVector(v4);
}
int main()
{
test08();
system("pause");
return 0;
}
2.2.3 vector的赋值操作
给vector容器进行赋值
//vector赋值操作
/*
函数原型:
vector& operator=(const vector &vec);//重载等号操作符
assign(beg, end);//将[beg, end)区间中的数据拷贝赋值给本身
assign(n,elem);//将n个elem拷贝赋值给本身
*/
void test02()
{
vector<int>v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
printVector(v1);
//赋值
vector<int> v2 = v1;
printVector(v2);
//assign
vector<int>v3;
v3.assign(v1.begin(), v1.end());
printVector(v3);
vector<int>v4;
v4.assign(10, 100);
printVector(v4);
}
2.2.4 vector的容量和大小
功能描述:对vector容器的容量和大小操作
//vector 容器得容量和大小
/*
empty(); //判断容器是否为空
capacity(); //容器的容量
size(); //返回容器中元素的个数
resize(int num);//重新指定容器的长度为num,若容器变长,则以默认值填充新位置。
//如果容器变短,则末尾超出容器长度的元素被删除。
resize(int num,elem);//重新指定容器的长度为num,若容器变长,则以elem值填充新位置。
//如果容器变短,则末尾超出容器长度的元素被删除
*/
void test03()
{
vector<int>v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
printVector(v1);
if (v1.empty())//为真代表容器为空
{
cout << "v1为空"<<endl;
}
else
{
cout << "v1不为空" << endl;
cout << "v1的容量为:" <<v1.capacity()<<endl;
cout << "v1的大小为:" << v1.size() << endl;
}
//重新指定大小
v1.resize(15);
cout << "v1的容量为:" << v1.capacity() << endl;
cout << "v1的大小为:" << v1.size() << endl;
printVector(v1);//如果重新指定的比原来长了,默认用0填充,也可以指定
v1.resize(5);
printVector(v1);//如果重新指定的比原来短了,超出部分删除
}
2.2.5 vector的插入和删除
//vector 插入和删除
/*
-push_back() 尾部插入元素
-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 test04()
{
vector<int>v1;
//尾插
for (int i = 0; i < 5; i++)
{
v1.push_back(i);
}
printVector(v1);
//尾删
v1.pop_back();
printVector(v1);
v1.insert(v1.begin(), 100);
v1.insert(v1.begin(),4, 100);
printVector(v1);
v1.erase(v1.begin());
printVector(v1);
/*v1.erase(v1.begin(), v1.end());
printVector(v1);*/
v1.clear();
printVector(v1);
}
2.2.6 vector的数据存取
//vector容器数据存取
//at(int idx) 返回所以dix所指的数据
//[] 返回所以dix所指的数据
//front() 返回容器中第一个数据元素
//back() 返回容器中最后一个数据元素
void test05()
{
vector<int>v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
for (int i = 0; i < v1.size(); i++)
{
cout << v1[i] << " ";
}
cout << endl;
for (int i = 0; i < v1.size(); i++)
{
cout << v1.at(i) << " ";
}
cout << endl;
cout << v1.front() << endl;
cout << v1.back() << endl;
}
2.2.7 vector互换容器
//vector 互换容器 实现两个容器元素互换
//swap(vec)
//1.基本使用
void test06()
{
vector<int>v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
printVector(v1);
vector<int>v2;
for (int i = 10; i >0; i--)
{
v2.push_back(i);
}
printVector(v2);
cout << "交换后:" << endl;
v1.swap(v2);
printVector(v1);
printVector(v2);
}
//2.实际用途
//巧用swap可以收缩内存空间
void test07()
{
vector<int>v;
for (int i = 0; i < 100000; i++)
{
v.push_back(i);
}
cout << "v的容量:" <<v.capacity() << endl;
cout << "v的大小:" <<v.size() << endl;
v.resize(3);//重新指定大小 大小变为3 容量不变
cout << "v的容量:" << v.capacity() << endl;
cout << "v的大小:" << v.size() << endl;
//巧用swap收缩
vector<int>(v).swap(v); //vector<int>(v) 匿名对象
cout << "v的容量:" << v.capacity() << endl;
cout << "v的大小:" << v.size() << endl;
}
2.2.8 vector预留空间
//vector容器 预留空间
//reserve(int len)
void test08()
{
vector<int>v;
//利用reserve预留空间
v.reserve(100000);
int num = 0; //统计开辟次数
int* p = NULL;
for (int i = 0; i < 100000; i++)
{
v.push_back(i);
if (p != &v[0])
{
p = &v[0];
num++;
}
}
cout << num << endl;
}
2.3 Deque容器
功能:
- 双端数组,可以对头端进行插入删除操作
deque与vector区别:
-
vector对于头部的插入删除效率低,数据量越大,效率越低
-
deque相对而言,对头部的插入删除速度回比vector快
-
vector访问元素时的速度会比deque快,这和两者内部实现有关
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gpZXpYXS-1602228009280)(C:\Users\leovo\AppData\Roaming\Typora\typora-user-images\image-20201007104902954.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LXgwDbiM-1602228009282)(C:\Users\leovo\AppData\Roaming\Typora\typora-user-images\image-20201007112558490.png)]
2.3.1 deque构造函数
功能描述:deque容器构造
#include<iostream>
#include<deque>
#include<algorithm>
using namespace std;
//deque双端数组
void printDeque(const deque<int>&d) //只读操作
{
for (deque<int>:: const_iterator it = d.begin(); it != d.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
//deque 构造函数
/*
deque<T> deqT; //默认构造形式
deque(beg,end); //构造函数将[beg,end)区间中的元素拷贝给本身。
deque(n,elem); //构造函数将n个elem拷贝给本身。
deque(const deque &deq);//拷贝构造函数
*/
void test01()
{
deque<int>d1;
for (int i = 0; i < 10; i++)
{
d1.push_back(i);
}
printDeque(d1);
deque<int>d2(d1.begin(), d1.end());
printDeque(d2);
deque<int>d3(10,100);
printDeque(d3);
deque<int>d4(d3);
printDeque(d4);
}
int main()
{
test08();
system("pause");
return 0;
}
2.3.2 deque 赋值操作
功能描述:给deque容器进行赋值
//deque容器 赋值操作
/*
deque& operator=(const deque &deq); //重载等号操作符
assign(beg,end); //将[beg, end)区间中的数据拷贝赋值给本身。
assign(n, elem); //将n个elem拷贝赋值给本身。
*/
void test02()
{
deque<int>d1;
for (int i = 0; i < 10; i++)
{
d1.push_back(i);
}
printDeque(d1);
deque<int>d2;
d2 = d1;
printDeque(d2);
deque<int>d3;
d3.assign(d2.begin(), d2.end());
printDeque(d3);
deque<int>d4;
d4.assign(10, 100);
printDeque(d4);
}
2.3.3 deque大小操作
//deque的大小操作 deque 没有容量概念
/*
deque.empty(); //判断容器是否为空
deque.size(); //返回容器中元素的个数
deque.resize(num); //重新指定容器的长度为num,若容器变长,则以默认值填充新位置。
deque.resize(num,elem); //如果容器变短,则末尾超出容器长度的元素被删除。
//重新指定容器的长度为num,若容器变长,则以elem值填充新位置。
//如果容器变短,则末尾超出容器长度的元素被删除。
*/
void test03()
{
deque<int>d1;
for (int i = 0; i < 10; i++)
{
d1.push_back(i);
}
printDeque(d1);
if (d1.empty())
{
cout << "d1为空!" << endl;
}
else
{
cout << "d1的大小:" << d1.size() << endl;
}
d1.resize(15,1);
printDeque(d1);
cout << "d1的大小:" << d1.size() << endl;
d1.resize(5);
printDeque(d1);
cout << "d1的大小:" << d1.size() << endl;
}
2.3.4 deque插入和删除
//deque 插入和删除
/*
两端插入操作:
push_back(elem);//在容器尾部添加—个数据
push_front(elem);//在容器头部插入一个数据
pop_back();//删除容器最后一个数据
pop_front();//删除容器第一个数据
指定位置操作:
insert(pos,elem);//在pos位置插入一个elem元素的拷贝,返回新数据的位置。
insert(pos,n,elem);//在pos位置插入n个elem数据,无返回值。
insert(pos,beg,end);//在pos位置插入[beg,end)区间的数据,无返回值。
clear();//清空容器的所有数据
erase(beg,end);//删除[beg,end)区间的数据,返回下一个数据的位置。
erase(pos);//删除pos位置的数据,返回下一个数据的位置。
*/
//1.两端插入操作
void test04()
{
deque<int>d1;
d1.push_back(10);
d1.push_back(20);
d1.push_front(100);
d1.push_front(200);
printDeque(d1);
d1.pop_back();
printDeque(d1);
d1.pop_front();
printDeque(d1);
}
void test05()
{
deque<int>d1;
d1.push_back(10);
d1.push_back(20);
d1.push_front(100);
d1.push_front(200);
printDeque(d1);
d1.insert(d1.begin(), 1000);
printDeque(d1);
d1.insert(d1.begin(),2, 10000);
printDeque(d1);
deque<int>d2;
d2.push_back(1);
d2.push_back(2);
d2.push_back(3);
d1.insert(d1.begin(), d2.begin(),d2.end());
printDeque(d1);
}
//删除
void test06()
{
deque<int>d1;
d1.push_back(10);
d1.push_back(20);
d1.push_front(100);
d1.push_front(200);
printDeque(d1);
deque<int>::iterator it=d1.begin();
it++;
d1.erase(it);
printDeque(d1);
d1.erase(d1.begin(), d1.end());
printDeque(d1);
d1.clear();
printDeque(d1);
}
2.3.5 deque数据存取
//deque 数据存取
/*
at(int idx) 返回所以dix所指的数据
[] 返回所以dix所指的数据
front() 返回容器中第一个数据元素
back() 返回容器中最后一个数据元素
*/
void test07()
{
deque<int>d1;
d1.push_back(10);
d1.push_back(20);
d1.push_front(100);
d1.push_front(200);
for (int i = 0; i < d1.size(); i++)
{
cout << d1[i] << " ";
}
cout << endl;
for (int i = 0; i < d1.size(); i++)
{
cout << d1.at(i) << " ";
}
cout << endl;
cout << "第一个元素为:" << d1.front() << endl;
cout << "最后一个元素为:" << d1.back() << endl;
}
2.3.6 deque 排序操作
//deque 容器排序
#include <algorithm> //算法头文件
void test08()
{
deque<int>d1;
d1.push_back(10);
d1.push_back(20);
d1.push_front(100);
d1.push_front(200);
printDeque(d1);
//排序
//支持随机访问的迭代器都可以利用sort算法直接对其进行排序
sort(d1.begin(), d1.end());//默认从小到大
printDeque(d1);
}
2.4 STL案例1-评委打分
#include<iostream>
#include<string>
#include<vector>
#include<deque>
#include<algorithm>
#include<time.h>
using namespace std;
//有5名选手,分别为:ABCDE,10个评委分别对每一名选手打分,去除最高分,最低分,取平均分
class Person
{
public :
Person(string name, int score)
{
this->m_Name = name;
this->m_Score = score;
}
string m_Name;
int m_Score;
};
void creatPerson(vector<Person>& v)
{
string nameSeed = "ABCDE";
for (int i = 0; i < 5; i++)
{
string name = "选手";
name += nameSeed[i];
int score = 0;
Person p(name, score);
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);
}
//排序
/*cout << "选手:" << it->m_Name << "打分" << endl;
for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++)
{
cout << *dit << " ";
}
cout << endl;*/
sort(d.begin(), d.end());
//去除最低分,最高分
d.pop_back();
d.pop_front();
int sum = 0;
for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++)
{
sum += *dit;
}
int avg = sum / d.size();
it->m_Score = avg;
}
}
void showScore(vector<Person> &v)
{
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "选手" << (*it).m_Name << " 得分:" << (*it).m_Score << endl;
}
}
int main()
{
//随机数种子
srand((unsigned int)time(NULL));
//1.创建5名选手
vector<Person>v;//存放选手的容器
creatPerson(v);
//测试u
/*for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名"<<(*it).m_Name << " ";
cout << "分数" << (*it).m_Score << " "<<endl;
}*/
//2.给5名选手打分
setScore(v);
//3.显示最后得分
showScore(v);
system("pause");
return 0;
}
2.5 stack容器
2.5.1 stack容器基本概念
概念:先进先出的数据结构,不允许有遍历行为 只能对栈顶进行操作
栈可以判断容器是否为空 empty
栈可以返回元素个数。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o14MuZOt-1602228009287)(C:\Users\leovo\AppData\Roaming\Typora\typora-user-images\image-20201007114938354.png)]
2.5.2 stack常用接口
#include<iostream>
#include<stack>
using namespace std;
//栈 先进后出 栈不允许遍历
//栈基本接口
/*
构造函数:
stack<T> stk;//stack采用模板类实现,stack对象的默认构造形式
stack( const stack &stk);//拷贝构造函数
赋值操作:
stack& operator=(const stack &stk);//重载等号操作符
数据存取:
push(elem);//向栈页添加元素
pop();//从栈顶移除第一个元素
top();//返回栈顶元素
大小操作:
empty();//判断堆栈是否为空
size();//返回栈的大小
*/
void test01()
{
stack<int>s;
s.push(10);
s.push(20);
s.push(30);
s.push(40);
cout << "栈的大小:" << s.size() << endl;
while(!s.empty())
{
cout << "栈顶元素为:"<<s.top() << endl;
//出栈
s.pop();
}
cout << "栈的大小:" << s.size() << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
2.6 Queue容器
2.5.1 queue容器基本概念
概念:先进先出的数据结构,有两个出口。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-g2ivVYWy-1602228009290)(C:\Users\leovo\AppData\Roaming\Typora\typora-user-images\image-20201007115813799.png)]
- 队列容器允许从一端新增元素,从另—端移除元素
- 队列中只有队头和队尾才可以被外界使用,因此队列不允许有遍历行为
- 队列中进数据称为—入队push
2.5.2 queue常用接口
#include<iostream>
#include<string>
#include<queue>
using namespace std;
//queue队列 先进先出 不允许遍历
//queue接口
/*
构造函数:
queue<T> que;//queue采用模板类实现,queue对象的默认构造形式
queue(const queue &que);//拷贝构造函数
赋值操作:
queue& operator=(const queue &que);//重载等号操作符
数据存取:
push(elem);//往队尾添加元素
pop();//从队头移除第一个元素
back();//返回最后一个元素
front();//返回第一个元素
大小操作:
empty();//判断堆栈是否为空
size();//返回栈的大小
*/
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
void test01()
{
queue<Person>q;
Person p1("唐僧", 30);
Person p2("孙悟空", 40);
Person p3("猪八戒", 50);
Person p4("沙和尚", 30);
q.push(p1);
q.push(p2);
q.push(p3);
q.push(p4);
cout << "队列的大小为:" << q.size() << endl;
//判断队列不为空,查看队头,队尾
while (!q.empty())
{
cout << "队头元素为--姓名:" << q.front().m_Name << "年龄:" << q.front().m_Age << endl;
cout << "队尾元素为--姓名:" << q.back().m_Name << "年龄:" << q.back().m_Age << endl;
q.pop();
}
cout << "队列的大小为:" << q.size() << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
2.7 List容器
2.7.1 list基本概念
功能:将数据进行链式存储
链表(list)是一种物理存储单元上非连续的存储结构,数据元素的逻辑顺序是通过链表中的指针链接实现的
链表的组成:链表由—系列结点组成
结点的组成:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域
STL中的链表是—个双向循环链表
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FAbMQtug-1602228009292)(C:\Users\leovo\AppData\Roaming\Typora\typora-user-images\image-20201007144834163.png)]
由于链表的存储方式并不是连续的内存空间,因此链表list中的迭代器只支持前移和后移,属于双向迭代器
list的优点:
- 采用动态存储分配,不会造成内存浪费和溢出
- 链表执行插入和删除操作十分方便,修改指针即可,不需要移动大量元素
list的缺点:
- 链表灵活,但是空间(指针域)和时间(遍历)额外耗费较大
- List有一个重要的性质,插入操作和删除操作都不会造成原有list迭代器的失效,这在vector是不成立的。
总结: ST L中List和vector是两个最常被使用的容器,各有优缺点
2.7.2 list构造函数
功能描述:创建list容器
#include<iostream>
#include<string>
#include<list>
using namespace std;
//打印函数
void printList(const list<int>&l)
{
for (list<int>::const_iterator it = l.begin(); it != l.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
//list构造函数
/*
函数原型:
list<T> lst;//list采用采用模板类实现.对象的默认构造形式:
list(beg,end);//构造函数将[beg, end)区间中的元素拷贝给本身。
list(n,elem);//构造函数将n个elem拷贝给本身。
list(cons list &lst);//拷贝构造函数。
*/
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(L1.begin(),L1.end());
printList(L2);
//拷贝构造
list<int>L3(L2);
printList(L3);
//n个元素elem
list<int>L4(10, 1000);
printList(L4);
}
int main()
{
test06();
system("pause");
return 0;
}
2.7.3 list赋值和交换
功能描述:给list容器进行赋值,以及交换list容器
//list赋值和交换
/*
函数原型:
assign(beg, end);//将[beg,end)区间中的数据拷贝赋值给本身。
assign(n, elem);//将n个elem拷贝赋值给本身。
list& operator=(const list &lst);//重载等号操作符
swap(lst);//将lst与本身的元素互换。
*/
voird printList(const List<int>&L)
{
for(List<int>::const_iterator it=L.begin();it!=L.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
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 = L1;//
printList(L2);
list<int>L3;
L3.assign(L2.begin(), L2.end());//
printList(L3);
list<int>L4;
L4.assign(10, 100);//
printList(L4);
//L1和L4交换
L1.swap(L4);
printList(L1);
printList(L4);
}
2.7.4 list大小操作
//list大小操作
/*函数原型:
size();//返回容器中元素的个数
empty();//判断容器是否为空
resize(num);//重新指定容器的长度为num,若容器变长,则以默认值填充新位置。
//如果容器变短,则末尾超出容器长度的元素被删除。
resize(num,elem);//重新指定容器的长度为num,若容器变长,则以elem值填充新位置。
//如果容器变短,则末尾超出容器长度的元素被删除。
*/
void test03()
{
list<int>L1;
L1.push_back(10);
L1.push_back(20);
L1.push_back(30);
L1.push_back(40);
printList(L1);
if (L1.empty())
{
cout<<"链表为空!"<<endl;
}
else
{
cout << "链表的大小为:" << L1.size() << endl;
}
L1.resize(10, 100);
printList(L1);
L1.resize(2);
printList(L1);
}
2.7.5 list删除和插入
功能描述:对list容器进行数据的插入和删除
//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(); //移除容器的所有数据
oerase(beg,end); //删除[beg,end)区间的数据,返回下一个数据的位置。
erase(pos); //删除pos位置的数据,返回下一个数据的位置。
remove(elem); //删除容器中所有与elem值匹配的元素。
*/
void test04()
{
list<int>L1;
L1.push_back(10);
L1.push_back(20);
L1.push_back(30);
L1.push_back(40);
L1.push_front(400);
L1.push_front(300);
L1.push_front(200);
L1.push_front(100);
printList(L1);
L1.insert(L1.begin(), 1000);
printList(L1);
L1.erase(L1.begin());
printList(L1);
L1.pop_back();
L1.pop_front();
printList(L1);
list<int>::iterator it = L1.begin();
L1.insert(++it, 10000);
printList(L1);
L1.erase(it);
//移除
L1.push_back(10000);
L1.push_back(10000);
L1.push_back(10000);
printList(L1);
L1.remove(10000);
printList(L1);
L1.clear();
printList(L1);
}
2.7.6 list数据存取
//list数据存取
//front() 返回第一个元素
//back() 返回最后一个元素
void test05()
{
list<int>l;
l.push_back(10);
l.push_back(20);
l.push_back(30);
l.push_back(40);
//l[0] 不可以用[]访问list容器中的元素
//l.at(0) 不可以用at()访问list容器中的元素
//原因是list本质是链表,不是用连续线性空间存储,迭代器不支持随机访问
cout << "第一个元素为:" << l.front() << endl;
cout << "最后一个元素为:" << l.back() << endl;
//迭代器不支持随机访问
list<int>:: iterator it = l.begin();
it++;//支持双向
it--;
//it=it+1 不支持随机访问
while (it != l.end())
{
cout << "第一个元素为:" <<*it++<< endl;
}
}
2.7.7 list反转和排序
//list反转和排序
//reverse() 反转链表
//sort() 排序
bool myCompare(int v1,int v2)
{
//降序 让第一个数大于第二个数
return v1 > v2;
}
void test06()
{
list<int>l;
l.push_back(50);
l.push_back(20);
l.push_back(40);
l.push_back(30);
l.push_back(10);
cout<<"反转前:"<<endl;
printList(l);
//反转
l.reverse();
cout<<"反转后:"<<endl;
printList(l);
//所有不支持随机访问迭代器的容器,不可以用标准算法
//不支持随机访问迭代器的容器,内部会提供一些对应算法
//sort(l.begin(),l.end())
l.sort();// 默认排序规则 从小到大 升序
printList(l);
l.sort(myCompare);//降序
printList(l);
}
#include<iostream>
#include<list>
#include<string>
using namespace std;
//案例描述:将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高
//排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序
class Person
{
public:
Person(string name, int age, int height)
{
this->m_Name = name;
this->m_Age = age;
this->m_Height = height;
}
string m_Name;
int m_Age;
int m_Height;
};
bool comparePerson(Person& p1, Person& p2)
{
//按照年龄做升序 年龄相同 按身高降序
if (p1.m_Age == p2.m_Age)
{
return p1.m_Height > p2.m_Height;
}
return p1.m_Age < p2.m_Age;
}
void test01()
{
list<Person>L;
//准备数据
Person p1("刘备", 35, 175);
Person p2("曹操", 45, 180);
Person p3("孙权", 40, 170);
Person p4("赵云", 25, 190);
Person p5("张飞", 35, 160);
Person p6("关羽", 35, 200);
L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
L.push_back(p5);
L.push_back(p6);
cout << "排序前:" << endl;
for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
{
cout << (*it).m_Name << " " << (*it).m_Age << " " << (*it).m_Height << " " << endl;
}
//排序
cout << "----------------------------" << endl;
cout << "排序后:" << endl;
L.sort(comparePerson);
for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
{
cout << (*it).m_Name << " " << (*it).m_Age << " " << (*it).m_Height << " " << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
2.8 Set容器
set基本概念
简介:
- 所有元素都会在插入时自动被排序
本质:
- set/multiset属于关联式容器,底层结构是用二叉树实现。
set和multiset区别:
- set不允许容器中有重复的元素
- multiset允许容器中有重复的元素
2.8.1 set构造和赋值
#include<iostream>
#include<string>
#include<set>
using namespace std;
void printSet(const set<int>& s)
{
for (set<int>::const_iterator it = s.begin(); it != s.end(); it++)
{
cout << *it << " ";
}
cout <<endl;
}
//set容器 赋值和构造
/*
构造:
set<T> st;//默认构造函数:
set(const set &st);//拷贝构造函数
赋值:
set& operator=(const set &st);//重载等号操作符
*/
void test01()
{
set<int>s1;
//set插入数据 只有insert
s1.insert(10);
s1.insert(40);
s1.insert(30);
s1.insert(20);
printSet(s1);
//set容器特点:所有元素插入时被自动排序 并且不允许插入重复的数据
set<int>s2(s1);
printSet(s2);
set<int>s3;
s3 = s2;
printSet(s3);
}
int main()
{
test08();
system("pause");
return 0;
}
2.8.2 set大小和交换
//set容器 大小和交换
//size() empty() swap(st) 不支持resize()重新指定大小
void test02()
{
set<int> s1;
s1.insert(10);
s1.insert(40);
s1.insert(30);
s1.insert(20);
printSet(s1);
if (s1.empty())
{
cout << "s1为空!" << endl;
}
else
{
cout << "s1不为空!" << endl;
cout << "s1的大小:" << s1.size() << endl;
}
set<int> s2;
s2.insert(100);
s2.insert(400);
s2.insert(300);
s2.insert(200);
cout << "交换前:" << endl;
printSet(s1);
printSet(s2);
s1.swap(s2);
cout << "交换后:" << endl;
printSet(s1);
printSet(s2);
}
2.8.3 set插入和删除
//set和multiset的区别
//set 不可以插入重复的值 set插入数据的同时会返回插入结果 返回插入十分成功
//multiset 可以插入重复的值
/*
insert(elem);//在容器中插入元素。
clear();//清除所有元素
erase(pos);//删除pos迭代器所指的元素,返回下一个元素的迭代器。
erase(beg,end);//删除区间[beg,end)的所有元素,返回下一个元素的迭代器。
erase(elem); //删除容器中值为elem的元素。
*/
void test03()
{
set<int> s1;
s1.insert(10);
s1.insert(40);
s1.insert(30);
s1.insert(20);
printSet(s1);
set<int>::iterator it = s1.begin();
set<int>::iterator st = s1.end();
it++;
s1.erase(it);
printSet(s1);
s1.erase(30);
printSet(s1);
//s1.erase(s1.begin(),s1.end());
s1.clear();
printSet(s1);
}
2.8.4 set查找和统计
//set容器的查找和统计
//find(key) 查找key是否存在 若存在 返回该键的元素的迭代器 若不存在 返回set.end()
//count(key) 统计key的元素个数
void test04()
{
set<int> s1;
//插入
s1.insert(10);
s1.insert(40);
s1.insert(30);
s1.insert(20);
printSet(s1);
//统计
cout << s1.count(10) << endl;
//查找
set<int>::iterator pos=s1.find(300);
if (pos != s1.end())
{
cout << "找到元素!" << *pos << endl;
}
else
{
cout << "没有找到元素!" << endl;
}
}
2.8.5 set和multiset的区别
//set和multiset的区别
//set不可以插入重复的值 set插入数据的同时会返回插入结果 返回插入十分成功
//multiset 不会检测数据,因此可以插入重复的值
void test05()
{
set<int>s;
pair<set<int>::iterator, bool> ret = s.insert(10); //对组
if (ret.second)
{
cout << "第一次插入成功!" << endl;
}
else
{
cout << "第一次插入失败!" << endl;
}
ret=s.insert(10);
if (ret.second)
{
cout << "第一次插入成功!" << endl;
}
else
{
cout << "第一次插入失败!" << endl;
}
multiset<int>ms;
ms.insert(10);
ms.insert(10);
for (multiset<int>::iterator it = ms.begin(); it != ms.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
2.8.6 pair使用 pair对组的创建
//pair队组创建
//方式一:pair<type,type> p(value1,value2)
//方式二:pair<type,type> p=make_pair(value1,value2)
void test06()
{
pair<string, int> p("TOM", 20);
cout << "姓名:" << p.first << "年龄:" << p.second<< endl;
pair<string, int> p2 = make_pair("amy", 18);
cout << "姓名:" << p2.first << "年龄:" << p2.second << endl;
}
2.8.7 set内置数据类型排序
set默认排序为从大到小
主要技术点:利用仿函数,可以改变排序规则
//set内置数据排序
class MyCompare
{
public:
bool operator()(const int v1, const int v2)const
{
return v1 > v2;
}
};
void test07()
{
set<int>s1;
s1.insert(10);
s1.insert(30);
s1.insert(40);
s1.insert(20);
s1.insert(50);
for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//指定排序规则为从大到小 插入之前指定规则
set<int, MyCompare>s2;
s2.insert(10);
s2.insert(30);
s2.insert(40);
s2.insert(20);
s2.insert(50);
for (set<int,MyCompare>::iterator it = s2.begin(); it != s2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
2.8.8 set自定义数据类型排序
//set容器自定义数据类型排序
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
class comparePerson
{
public:
bool operator()(const Person& p1, const Person& p2)const
{
return p1.m_Age > p2.m_Age;//按年龄降序
}
};
void test08()
{
set<Person, comparePerson> s;
Person p1("刘备",24);
Person p2("关羽", 27);
Person p3("张飞", 29);
Person p4("赵云", 21);
s.insert(p1);
s.insert(p2);
s.insert(p3);
s.insert(p4);
for (set<Person,comparePerson>::iterator it = s.begin(); it != s.end(); it++)
{
cout << "姓名"<<it->m_Name<< " 年龄:"<<it->m_Age<<endl;
}
cout << endl;
}
2.9 Map容器
简介:
- map中所有元素都是pair
- pair中第一个元素为key(键值),起到索引作用,第二个元素为value(实值)
- 所有元素都会根据元素的键值自动排序
本质:
map/multimap属于关联式容器,底层结构是用二叉树实现。
优点:
- 可以根据key值快速找到value值
map和multi map区别:
-
map不允许容器中有重复key值元素
-
multi map允许容器中有重复key值元素
2.9.1 map 构造和赋值
功能描述:对map容器进行构造和赋值操作
#include<iostream>
#include<map>
#include<string>
using namespace std;
void printMap(map<int, int>&m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key=" << (*it).first << " value= " << it->second << endl;
}
cout << endl;
}
//map容器构造和赋值
/*
构造:
map<T1,T2> mp;//map默认构造函数:
map(const map &mp);//拷贝构造函数
赋值:
map& operator=(const map &mp);//重载等号操作符
*/
void test01()
{
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(3, 30));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(4, 40));
printMap(m);
//拷贝构造
map<int, int>m2(m);
printMap(m2);
map<int, int>m3;
m3 = m2;
printMap(m3);
}
总结:Map容器中所以元素都成对出现,插入时要使用对组
2.9.2 map 大小和交换
功能描述:统计map容器大小以及交换map容器
//map容器的大小和交换
/*
函数原型:
size();//返回容器中元素的数目
empty();//判断容器是否为空
swap(st);//交换两个集合容器
*/
void test02()
{
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(3, 30));
m.insert(pair<int, int>(4, 40));
printMap(m);
if (m.empty())
{
cout << "map为空!" << endl;
}
else
{
cout << "map不为空!" << endl;
cout << "m的大小为:" << m.size() << endl;
}
//交换
map<int, int>m2;
m2.insert(pair<int, int>(5, 50));
m2.insert(pair<int, int>(6, 60));
m2.insert(pair<int, int>(7, 70));
m2.insert(pair<int, int>(8, 80));
cout << "交换前:" << endl;
printMap(m);
printMap(m2);
cout << "交换后:" << endl;
m.swap(m2);
printMap(m);
printMap(m2);
}
2.9.3 map 插入和删除
//map的插入和删除
/*
函数原型:
insert(elem);//在容器中插入元素。
clear();//清除所有元素
erase(pos);//删除pos迭代器所指的元素,返回下一个元素的迭代器。
erase(beg,end);//删除区间[beg,end)的所有元素,返回下一个元素的迭代器。
erase(key);//删除容器中值为key的元素。
*/
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));
//第二种
m.insert(make_pair(5, 50));
//第三种
m.insert(map<int, int>::value_type(6, 60));
//第四种
m[7] = 70;
//[]不建议用 用途:可以利用key访问到value
cout<<m[5]<<endl;
printMap(m);
m.erase(m.begin());
printMap(m);
m.erase(3);//按照key删除
printMap(m);
m.clear();
m.erase(m.begin(), m.end());
printMap(m);
}
2.9.4 map 查找和统计
//map查找和统计
//find(key) //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();
//count(key);//统计key的元素个数
void test04()
{
map<int, int>m;
m.insert(make_pair(1, 10));
m.insert(make_pair(2, 20));
m.insert(make_pair(3, 30));
m.insert(make_pair(4, 40));
map<int,int>::iterator pos=m.find(3);
if (pos != m.end())
{
cout << "查到元素 key=" << pos->first << " value=" << (*pos).second << endl;
}
else
{
cout << "未找到元素!" << endl;
}
int num = m.count(3);
cout << "key为3的个数为:" << num << endl;
}
2.9.5 map 排序
map默认排序规则从小到大。
利用仿函数改变排序规则。
//map排序
//内置数据类型
class CompareMap
{
public:
bool operator()(const int v1, const int v2)const
{
return v1 > v2;
}
};
void test05()
{
map<int, int>m;
m.insert(make_pair(1, 10));
m.insert(make_pair(2, 20));
m.insert(make_pair(5, 50));
m.insert(make_pair(3, 30));
m.insert(make_pair(4, 40));
printMap(m);
map<int, int, CompareMap>m2;//提前指定排序规则
m2.insert(make_pair(1, 10));
m2.insert(make_pair(2, 20));
m2.insert(make_pair(5, 50));
m2.insert(make_pair(3, 30));
m2.insert(make_pair(4, 40));
for (map<int, int, CompareMap>::iterator it = m2.begin(); it != m2.end(); it++)
{
cout << "key=" << (*it).first << " value= " << it->second << endl;
}
cout << endl;
}
//自定义数据类型
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
class comparePerson
{
public:
bool operator()( const Person& p1, const Person& p2)const
{
return p1.m_Age > p2.m_Age;
}
};
void test06()
{
map<Person, Person,comparePerson>m;
Person p1("A", 10);
Person p2("B", 30);
Person p3("C", 50);
Person p4("D", 30);
Person p5("E", 20);
Person p6("F", 40);
m.insert(pair<Person, Person>(p1, p2));
m.insert(pair<Person, Person>(p3, p4));
m.insert(pair<Person, Person>(p5, p6));
for (map<Person, Person, comparePerson>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key_name:" << it->first.m_Name << " key_age:" << it->first.m_Age
<< " value_name:" << (*it).first.m_Name << " value_age:" << (*it).second.m_Age << endl;
}
cout << endl;
}
int main()
{
test06();
system("pause");
return 0;
}
2.10 STL案例2-员工分组
公司招聘了10个员工,10名员工进入公司后,需要指派员工在哪个部门工作
员工信息有:姓名,工资 组成;部门分为:策划、美术、研发
随机给10名员工分配部门和工资。
通过multimap进行信息的插入 key(部门编号) value(员工)。
实现步骤:
1.创建10名员工,放到vector中
⒉遍历vector容器,取出每个员工,进行随机分组
3.分组后,将员工部门编号作为key,具体员工作为value,放入到multimap容器中
4.分部门显示员工信息
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<time.h>
#define CHEHUA 0
#define MEISHU 1
#define YANFA 2
using namespace std;
class Worker
{
public:
string m_Name;
int m_Salary;
};
void creatWorker(vector<Worker>& v)
{
string nameSeed = "ABCDEFGHIJ";
for (int i = 0; i < 10; i++)
{
Worker worker;
worker.m_Name = "员工";
worker.m_Name+=nameSeed[i];
worker.m_Salary = rand() % 3000 + 2000;
v.push_back(worker);
}
}
void setGroup(vector<Worker>& v, multimap<int, Worker>& m)
{
for (vector<Worker>::iterator it = v.begin(); it != v.end(); it++)
{
//产生随机部门标号
int depId = rand() % 3;//0 1 2
//将员工插入到分组中
m.insert(make_pair(depId, *it));
}
}
void showWorkerByGroup(multimap<int, Worker>& m)
{
/*for (multimap<int, Worker>::iterator it=m.begin();it!=m.end();it++)
{
if ((*it).first == 0)
{
cout << "策划部门:";
cout << "姓名:" << it->second.m_Name << " 薪水:" << (*it).second.m_Salary << endl;
}
else if ((*it).first == 1)
{
cout << "美术部门:" ;
cout << "姓名:" << it->second.m_Name << " 薪水:" << (*it).second.m_Salary << endl;
}
else
{
cout << "研发部门:";
cout << "姓名:" << it->second.m_Name << " 薪水:" << (*it).second.m_Salary << endl;
}
cout << endl;
}*/
cout << "策划部门:" << endl;
multimap<int, Worker>::iterator pos = m.find(CHEHUA);
int count = m.count(CHEHUA);//统计具体人数
int index = 0;
for (; pos != m.end() && index < count; pos++, index++)
{
cout << "姓名:" << pos->second.m_Name << " 薪水:" << (*pos).second.m_Salary << endl;
}
cout << "---------------" << endl;
cout << "美术部门:" << endl;
pos = m.find(MEISHU);
count = m.count(MEISHU);//统计具体人数
index = 0;
for (; pos != m.end() && index < count; pos++, index++)
{
cout << "姓名:" << pos->second.m_Name << " 薪水:" << (*pos).second.m_Salary << endl;
}
cout << "---------------" << endl;
cout << "研发部门:" << endl;
pos = m.find(YANFA);
count = m.count(YANFA);//统计具体人数
index = 0;
for (; pos != m.end() && index < count; pos++, index++)
{
cout << "姓名:" << pos->second.m_Name << " 薪水:" << (*pos).second.m_Salary << endl;
}
}
int main()
{
srand((unsigned int)time(NULL));
//1.创建员工
vector<Worker> vWorker;
creatWorker(vWorker);
测试
//for (vector<Worker>::iterator it = vWorker.begin(); it != vWorker.end(); it++)
//{
// cout << "姓名: " << it->m_Name << " 工资:" << (*it).m_Salary << endl;
//}
//cout << endl;
//员工分组
multimap<int, Worker> mWorker;
setGroup(vWorker, mWorker);
//3.分组显示员工
showWorkerByGroup(mWorker);
system("pause");
return 0;
}
3.函数对象
3.1函数对象
3.3.1 函数对象概念
概念:
重载函数调用操作符的类,其对象常称为函数对象
函数对象使用重载的(时,行为类似函数调用,也叫仿函数
本质:
函数对象(仿函数)是一个类,不是一个函数
3.3.2 函数对象使用
特点:
- 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
- 函数对象超出普通函数的概念,函数对象可以有自己的状态
- 函数对象可以作为参数传递
#include<iostream>
#include<string>
using namespace std;
//函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
class MyAdd
{
public:
int operator()(int v1,int v2)
{
return v1+v2;
}
}
void test01()
{
MyAdd myadd;
cout<<myadd(10,10)<<endl;
}
//函数对象超出普通函数的概念,函数对象可以有自己的状态
class MyPrint
{
public:
MyPrint()
{
this>count=0;
}
void operator()(string test)
{
cout<<test<<endl;
this->count++;
}
int count;
}
void test02()
{
MyPrint myPrint;
myPrint("fjshfkj");
myPrint("fjshfkj");
myPrint("fjshfkj");
myPrint("fjshfkj");
cout<<"myPrint的调用次数"<<myPrint.count<<endl;
}
//函数对象可以作为参数传递
void doPrint(MyPrint& mp,string test)
{
mp(test);
}
void test03()
{
MyPrint myPrint;
doPrint(myPrint,"C++");
}
int main()
{
test01();
test02();
test03();
system("pause");
return 0;
}
3.2谓词
3.2.1谓词的概念
谓词: 返回Bool类型的仿函数称为谓词
- 如果operator()接受一个参数,叫做一元谓词
- 如果operator()接受二个参数,叫做二元谓词
3.2.2一元谓词
#include<iostream>
#include <string>
#include<vector>
#include<algorithm>
using namespace std;
class GreaterFive
{
public:
bool operator()(int val)const
{
return val > 5;
}
};
//一元谓词
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//查找容器中有没有大于5的数字
//GreaterFive() 匿名函数对象
vector<int>::iterator it=find_if(v.begin(), v.end(), GreaterFive());//find_if 按条件查找
if (it == v.end())
{
cout << "未找到" << endl;
}
else
{
cout << "找到:" << (*it)<<endl;
}
}
int main()
{
test02();
system("pause");
return 0;
}
3.2.3二元谓词
//二元谓词
class MySort
{
public:
bool operator()(int val1, int val2)const
{
return val1 > val2;
}
};
void test02()
{
vector<int>v;
v.push_back(10);
v.push_back(40);
v.push_back(20);
v.push_back(30);
v.push_back(50);
sort(v.begin(),v.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//使用函数对象 改变算办法策略 变为排序规则为从大到小
sort(v.begin(), v.end(), MySort());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
test02();
system("pause");
return 0;
}
3.3内建函数对象
内建函数对象意义
概念:
STL内建了—些函数对象
分类:
- 算术仿函数
- 关系仿函数
- 逻辑仿函数
关系仿函数
逻辑仿函数
用法:
-
这些仿函数所产生的对象,用法和一般函数完全相同
-
使用内建函数对象,需要引入头文件
#include<functional>
3.3.1算术仿函数
功能描述:实现四则运算
其中negate是一元运算,其他都是二元运算
仿函数原型:
template<class T> T plus<T>//加法仿函数
template<class T> T minus<T>//减法仿函数
template<class T> T multiplies<T>//乘法仿函数
template<class T> T divides<T>//除法仿函数
template<class T> T modulus<T>//取模仿函数
template<class T> T negate<T>//取反仿函数
#include<iostream>
#include<functional>
using namespace std;
//template<class T> T negate<T>//取反仿函数—————一元仿函数
void test01()
{
negete<int>n;
cout<<n(50);//输出-50
}
//template<class T> T plus<T>//加法仿函数---二元仿函数
void test02()
{
plus<int>
}
int main()
{
test01();
system("pause");
return 0;
}
3.3.2关系仿函数
功能描述:实现关系对比
仿函数原型:
template<class T> bool equal_to<T>//等于
template<class T> bool not_equal_to<T>//不等于
template<class T> bool greater<T>//大于
template<class T> bool greater_equal<T>//大于等于
template<class T> bool less<T>//小于
template<class T> bool less_equal<T>//小于等于
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
//template<class T> bool greater<T>//大于
class MyCompare
{
public:
bool operator()(int v1,int v2)
{
return v1>v2;
}
}
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(10);
v.push_back(10);
v.push_back(10);
v.push_back(10);
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
//自己实现的排序
sort(v.begin(),v.end(),MyCompare());
//内建函数对象
sort(v.begin(),v.end(),greater<int>());
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
3.3.3逻辑仿函数
功能描述:实现逻辑运算
函数原型:
template<class T> bool logical_and<T>//逻辑与
template<class r> bool logical_or<T>//逻辑或
templateclass T> bool logical_not<T>//逻辑非
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
//templateclass 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);
for(vector<bool>::iterator it=v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
//利用逻辑非 将容器v搬运到容器 v2中
vector<bool>v2;
v2.resize(v.size());
transform(v.begin(),v.end(),v2.begin(),logical_not());
for(vector<bool>::iterator it=v2.begin();it!=v2.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
4. STL常用算法
算法主要是由头文件<algorithm><functional><numeric>组成。
- <algorithm>是所有STL头文件中最大的一个,范围涉及到比较、交换、查找、遍历操作、复制、修改等等
- <numeric>体积很小,只包括几个在序列上面进行简单数学运算的模板函数
- <functional>定义了—些模板类,用以声明函数对象。
4.1常用遍历算法
4.1.1 for_each
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
//利用遍历算法for_each
//普通函数
void print01(int val)
{
cout << val << " ";
}
//仿函数
class print02
{
public:
void operator()(int val)const
{
cout << val << " ";
}
};
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), print01);
cout << endl;
for_each(v.begin(), v.end(), print02());//print02 匿名函数对象
cout << endl;
}
//find
void test03()
{
}
int main()
{
test03();
system("pause");
return 0;
}
4.1.2 transform
//transform 将一个容器搬运到另一个容器
class Transform
{
public:
int operator()(int v)const
{
return v+100;
}
};
void test02()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>v2;//目标容器
v2.resize(v.size());//目标容器提前开辟空间
transform(v.begin(), v.end(), v2.begin(), Transform());
for_each(v.begin(), v.end(), print02());
cout << endl;
for_each(v2.begin(), v2.end(), print02());
}
4.2常用查找算法
4.2.1 find
#include<iostream>
#include<string>
using namespace std;
#include <algorithm>
#include<vector>
//1.find 查找指定元素 找到返回指定元素的迭代器 找不到返回end()迭代器
//(1)查找内置数据类型
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>::iterator it= find(v.begin(), v.end(), 5);
if (it == v.end())
{
cout << "没有找到!" << endl;
}
else
{
cout << "找到:" ;
cout << *it << endl;
}
}
//自定义数据类型
class Person
{
public:
Person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
//重载== 底层find知道如何对比person数据类型
bool operator==(const Person&p)
{
if (this->m_name == p.m_name &&this->m_age==p.m_age)
{
return true;
}
}
string m_name;
int m_age;
};
void test02()
{
vector<Person>v;
Person p1("A", 10);
Person p2("B", 20);
Person p3("C", 30);
Person p4("D", 40);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
Person pp("fd", 10);
vector<Person>::iterator it = find(v.begin(), v.end(), pp);
if (it == v.end())
{
cout << "没有找到!" << endl;
}
else
{
cout << "找到!"<<endl;
cout << it->m_name<<" "<<it->m_age << endl;
}
}
4.2.2 find_if
//2.find_if 按条件查找 返回迭代器
//(1)内置数据类型
class Greater
{
public:
bool operator()(int val)const
{
return val > 5;
}
};
void test03()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>::iterator it = find_if(v.begin(), v.end(), Greater());
if (it == v.end())
{
cout << "没有找到!" << endl;
}
else
{
cout << "找到大于5的数字:" ;
cout << *it << endl;
}
}
//(2)自定义数据类型
class Person2
{
public:
Person2(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
bool operator==(const Person& p)
{
if (this->m_name == p.m_name && this->m_age == p.m_age)
{
return true;
}
}
string m_name;
int m_age;
};
class Greater20
{
public:
bool operator()(const Person2& p)const
{
return p.m_age > 20;
}
};
void test04()
{
vector<Person2>v;
Person2 p1("A", 10);
Person2 p2("B", 20);
Person2 p3("C", 30);
Person2 p4("D", 40);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
//找年龄大于20的人
vector<Person2>::iterator it = find_if(v.begin(), v.end(), Greater20());
if (it == v.end())
{
cout << "没有找到!" << endl;
}
else
{
cout << "找到: 姓名:" << it->m_name << " 年龄:" << it->m_age << endl;
}
}
4.2.3 adjacent_find
//3.adjacent_find 查找相邻重复元素 返回相邻重复元素第一个位置的迭代器
void test05()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(50);
v.push_back(40);
v.push_back(30);
v.push_back(20);
v.push_back(30);
v.push_back(40);
vector<int>::iterator pos = adjacent_find(v.begin(), v.end());
if (pos == v.end())
{
cout << "没有找到!" << endl;
}
else
{
cout << *it << endl;
}
}
4.2.4 count
//5.count 算法 统计元素个数
// begin() end() value
//(1)内置数据类型
void test07()
{
vector<int>v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(3);
v.push_back(4);
v.push_back(3);
int num = count(v.begin(), v.end(), 3);
cout << num << endl;
}
//(2)自定义数据类型
class Person3
{
public:
Person3(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
bool operator==(const Person3& p)
{
if (this->m_age == p.m_age)
{
return true;
}
else
{
return false;
}
}
string m_name;
int m_age;
};
void test08()
{
vector<Person3>v;
Person3 p1("A", 10);
Person3 p2("B", 20);
Person3 p3("C", 30);
Person3 p4("B", 20);
Person3 p5("C", 30);
Person3 p6("D", 40);
Person3 p7("D", 40);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
v.push_back(p6);
v.push_back(p7);
Person3 p("D", 40);
int num = count(v.begin(), v.end(), p);
cout << num << endl;
}
4.2.5 count_if
//count_if 按条件统计指定元素个数 谓词
//(1)内置数据类型
class Greater2
{
public:
bool operator()(int val)const
{
return val > 2;
}
};
void test09()
{
vector<int>v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(3);
v.push_back(2);
v.push_back(1);
v.push_back(4);
int num = count_if(v.begin(), v.end(), Greater2());
cout << num << endl;
}
//自定义数据类型
class Person4
{
public:
Person4(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
bool operator==(const Person4& p)
{
if (this->m_age == p.m_age)
{
return true;
}
else
{
return false;
}
}
string m_name;
int m_age;
};
class Greater30
{
public:
bool operator()(const Person4& p)
{
return p.m_age > 30;
}
};
void test10()
{
vector<Person4>v;
Person4 p1("A", 10);
Person4 p2("B", 20);
Person4 p3("C", 30);
Person4 p4("B", 20);
Person4 p5("C", 30);
Person4 p6("D", 40);
Person4 p7("D", 40);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
v.push_back(p6);
v.push_back(p7);
int num = count_if(v.begin(), v.end(), Greater30());
cout << num << endl;
}
4.2.6 binary_search
在无序序列中不可用
//4.binary_search 二分查找 查找指定元素是否存在 返回true或者false
//在无序序列中不可用 beg end value
void test06()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
v.push_back(2);
//容器必须有序 无序序列结果不可知
sort(v.begin(), v.end());
//查找容器中是否有9 元素
bool ret=binary_search(v.begin(), v.end(), 9);
if (ret)
{
cout << "找到!" << endl;
}
else
{
cout << "没有找到!" << endl;
}
}
int main()
{
test10();
system("pause");
return 0;
}
4.3常用排序算法
4.3.1 sort
#include<iostream>
#include<string>
#include<functional>
#include<time.h>
using namespace std;
#include <algorithm>
#include<vector>
//常用排序算法
//sort() 对容器内元素进行排序
class Greater
{
public:
bool operator()(int val1, int val2)const
{
return val1 > val2;
}
};
void test01()
{
vector<int>v;
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(2);
v.push_back(6);
v.push_back(5);
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
sort(v.begin(), v.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//改变为降序
sort(v.begin(), v.end(), greater<int>());
//sort(v.begin(), v.end(), Greater());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
test03();
system("pause");
return 0;
}
4.3.2 random_shuffle
//random_shuffle 洗牌 指定范围内的元素随机调整次序
void test02()
{
srand((unsigned int)time(NULL));//按系统时间做随机数
vector<int>v;
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(2);
v.push_back(6);
v.push_back(5);
sort(v.begin(), v.end(), greater<int>());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//利用洗牌算法打乱
random_shuffle(v.begin(), v.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
4.3.3 merge
merge 两个容器合并,并存储到另一个容器中
两个容器必须为有序的
void test03()
{
vector<int>v;
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(2);
v.push_back(6);
v.push_back(5);
sort(v.begin(), v.end());
vector<int>v2;
v2.push_back(10);
v2.push_back(30);
v2.push_back(40);
v2.push_back(20);
v2.push_back(60);
v2.push_back(50);
sort(v2.begin(), v2.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
for (vector<int>::iterator it = v2.begin(); it != v2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
vector<int>v3;
//提前分配内存空间
v3.resize(v.size() + v2.size());
merge(v.begin(), v.end(), v2.begin(), v2.end(),v3.begin());
for (vector<int>::iterator it = v3.begin(); it != v3.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
4.3.4 reverse
//reverse 将容器内的元素反转
void myprint(int val)
{
cout<<val<<" ";
}
class MyPrint
{
public:
void operator()(int val)const
{
cout<<val<<" ";
}
}
void test04()
{
vector<int>v;
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(2);
v.push_back(6);
v.push_back(5);
reverse(v.begin(), v.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
//for_each(v.begin(),v.end(),myprint);
//for_each(v.begin(),v.end(),MyPrint());
cout << endl;
}
4.4常用拷贝和替换算法
4.4.1 copy
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
//常用拷贝和替换算法
//1.copy()
void myPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>v2;
//提前开辟空间
v2.resize(v.size());
copy(v.begin(), v.end(), v2.begin());
/*for (vector<int>::iterator it = v2.begin(); it != v2.end(); it++)
{
cout << *it << " ";
}
cout << endl;*/
for_each(v2.begin(), v2.end(), myPrint);
cout << endl;
}
int main()
{
test04();
system("pause");
return 0;
}
4.4.2 replace
//2.replace() 将指定区间范围内的旧元素替换为新元素
class MyPrint
{
public:
void operator()(int val)const
{
cout << val << " ";
}
};
void test02()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i+10);
}
cout << "替换前:";
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
cout << "替换后:";
replace(v.begin(), v.end(), 10, 1000);//reeplace(begin,end,oldvalue,newvalue)
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
}
4.4.3 replace_if
//3.replace_if(begin,end,谓词(条件),newvalue) 将指定区间范围内 满足条件的元素 替换为新元素
class Greater13
{
public:
bool operator()(int val)const
{
return val >= 13;
}
};
void test03()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i + 10);
}
cout << " 替换前:";
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
//将大于等于 30替换为3000
replace_if(v.begin(), v.end(), Greater13(), 3000);
for_each(v.begin(), v.end(), MyPrint());
}
4.4.4 swap
//swap(container c1,container c2) 互换两个容器中的所有元素 同种类型的容器
void test04()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v2.push_back(i+100);
}
cout << "交换前:" << endl;
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
for_each(v2.begin(), v2.end(), MyPrint());
cout << endl;
swap(v, v2);
cout << "交换后:" << endl;
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
for_each(v2.begin(), v2.end(), MyPrint());
cout << endl;
}
4.5常用算术生成算法
4.5.1 accumulate
常用算术生成算法 ,使用时包含的头文件为
#include<numeric>
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<numeric>
using namespace std;
//1.accumulate() 累加
void test01()
{
vector<int>v;
for (int i = 0; i <= 100; i++)
{
v.push_back(i);
}
int total=accumulate(v.begin(), v.end(), 0);//位置参数3是一个起始累加值
cout <<total<< endl;
}
int main()
{
test02();
system("pause");
return 0;
}
4.5.2 fill
//2.fill() 向容器中填充指定的元素
void myPrint(int val)
{
cout << val << " ";
}
void test02()
{
vector<int>v;
v.resize(10);
//后期重新填充
fill(v.begin(), v.end(), 100);
for_each(v.begin(), v.end(), myPrint);
cout << endl;
}
4.6常用集合算法
4.6.1 set_intersection
求两个容器的交集 两个容器必须有序
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<numeric>
using namespace std;
//常用集合算法
//1. set_intersection 求两个容器的交集 两个容器必须有序
void myPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i <10; i++)
{
v1.push_back(i);
v2.push_back(i + 5);
}
vector<int>vTarget;
vTarget.resize(min(v1.size(), v2.size()));//开辟空间需要从两个容器中取最小值
//返回值是交集中最后一个元素的位置
vector<int>::iterator itEnd=set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
for_each(vTarget.begin(), itEnd, myPrint);
cout << endl;
}
int main()
{
test03();
system("pause");
return 0;
}
4.6.2 set_union
求两个容器的并集 两个容器必须有序
//2.set_union 求两个容器的并集
void test02()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 5);
}
vector<int>vTarget;
//开辟空间两个容器相加
Target.resize(v1.size()+v2.size());
//返回值是交集中最后一个元素的位置
vector<int>::iterator itEnd = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
for_each(vTarget.begin(), itEnd, myPrint);
cout << endl;
}
4.6.3 set_difference
求两个容器的差集 两个容器必须有序
//set_difference 求两个容器的差集
void test03()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 5);
}
vector<int>vTarget;
//开辟空间两个容器的最大值
vTarget.resize(max(v1.size() , v2.size()));
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;
}
替换为新元素
class Greater13
{
public:
bool operator()(int val)const
{
return val >= 13;
}
};
void test03()
{
vectorv;
for (int i = 0; i < 10; i++)
{
v.push_back(i + 10);
}
cout << " 替换前:";
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
//将大于等于 30替换为3000
replace_if(v.begin(), v.end(), Greater13(), 3000);
for_each(v.begin(), v.end(), MyPrint());
}
#### 4.4.4 swap
```c++
//swap(container c1,container c2) 互换两个容器中的所有元素 同种类型的容器
void test04()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v2.push_back(i+100);
}
cout << "交换前:" << endl;
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
for_each(v2.begin(), v2.end(), MyPrint());
cout << endl;
swap(v, v2);
cout << "交换后:" << endl;
for_each(v.begin(), v.end(), MyPrint());
cout << endl;
for_each(v2.begin(), v2.end(), MyPrint());
cout << endl;
}
4.5常用算术生成算法
4.5.1 accumulate
常用算术生成算法 ,使用时包含的头文件为
#include<numeric>
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<numeric>
using namespace std;
//1.accumulate() 累加
void test01()
{
vector<int>v;
for (int i = 0; i <= 100; i++)
{
v.push_back(i);
}
int total=accumulate(v.begin(), v.end(), 0);//位置参数3是一个起始累加值
cout <<total<< endl;
}
int main()
{
test02();
system("pause");
return 0;
}
4.5.2 fill
//2.fill() 向容器中填充指定的元素
void myPrint(int val)
{
cout << val << " ";
}
void test02()
{
vector<int>v;
v.resize(10);
//后期重新填充
fill(v.begin(), v.end(), 100);
for_each(v.begin(), v.end(), myPrint);
cout << endl;
}
4.6常用集合算法
4.6.1 set_intersection
求两个容器的交集 两个容器必须有序
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<numeric>
using namespace std;
//常用集合算法
//1. set_intersection 求两个容器的交集 两个容器必须有序
void myPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i <10; i++)
{
v1.push_back(i);
v2.push_back(i + 5);
}
vector<int>vTarget;
vTarget.resize(min(v1.size(), v2.size()));//开辟空间需要从两个容器中取最小值
//返回值是交集中最后一个元素的位置
vector<int>::iterator itEnd=set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
for_each(vTarget.begin(), itEnd, myPrint);
cout << endl;
}
int main()
{
test03();
system("pause");
return 0;
}
4.6.2 set_union
求两个容器的并集 两个容器必须有序
//2.set_union 求两个容器的并集
void test02()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 5);
}
vector<int>vTarget;
//开辟空间两个容器相加
Target.resize(v1.size()+v2.size());
//返回值是交集中最后一个元素的位置
vector<int>::iterator itEnd = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
for_each(vTarget.begin(), itEnd, myPrint);
cout << endl;
}
4.6.3 set_difference
求两个容器的差集 两个容器必须有序
//set_difference 求两个容器的差集
void test03()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 5);
}
vector<int>vTarget;
//开辟空间两个容器的最大值
vTarget.resize(max(v1.size() , v2.size()));
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;
}