个人笔记——C++ STL

C++ STL

vector容器浅涉

基本使用——存放普通数据类型

#include <iostream>
#include <vector>
#include <algorithm> //标准算法头文件
using namespace std;

//vector容器来存放内置的数据类型

void myPrint(int val)
{
	cout << val << endl;
}

void test01()
{
	//创建一个vector容器,可以看作数组
	vector<int> v;

	//向容器中插入数据
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);

	//通过迭代器访问容器中的数据
	vector<int>::iterator itBegin = v.begin(); //起始迭代器,指向容器第一个元素
	vector<int>::iterator itEnd = v.end(); //结束迭代器,指向容器中最后一个元素的下一个位置

	//第一种遍历方式
	while(itBegin != itEnd)
	{
		cout << *itBegin << endl;
		itBegin++;
	}

	//第二种遍历方式(常用)
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << endl;
	}

	//第三种遍历方式,需要引用标准算法头文件——<algorithm>
	for_each(v.begin(), v.end(), myPrint);
	
}

int main()
{
	test01();

	system("pause");
	return 0;
}

存放自定义数据类型

#include <iostream>
#include <vector>
#include <algorithm>
#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("ddd", 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 << "\t年龄" << (*it).m_age << endl;
		//也可以用it->m_name获取
	}
	
}

//存放自定义类型的指针
void test02()
{
	vector<Person*>v;
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);
	Person p5("ddd", 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 << "\t年龄" << (*it)->m_age << endl;
	}
}

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

vector容器嵌套容器

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
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++)
	{
		//*it 即容器 vector<int>
		for (vector<int>::iterator vit = (*it).begin(); vit != (*it).end(); vit++)
		{
			cout << *vit << " ";
		}
		cout << endl;
	}
}

int main()
{
	test01();

	system("pause");
	return 0;
}

vector容器详解

  • vector容器的迭代器
    在这里插入图片描述

vector构造函数

函数原型:

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

示例:

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

	//拷贝构造
	vector<int>v4(v3);
	printVector(v4);
}

int main()
{
	test01();

	system("pause");
	return 0;
}

赋值操作

功能描述:
给vector容器进行赋值

函数原型:

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

示例:

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

	//赋值 operator=
	vector<int> v2;
	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);
}

int main()
{
	test01();

	system("pause");
	return 0;
}

vector容量和大小

功能描述:
对vector容器的容量和大小操作

函数原型:

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

示例:

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

	if(v1.empty()) //为真则代表容器为空
	{
		cout << "v1为空" << endl;
	}
	else
	{
		cout << "v1不为空" << endl;
		cout << "v1容量为:" << v1.capacity() << endl;  //返回13
		cout << "v1的size为:" << v1.size() << endl;
	}

	//重新指定大小
	v1.resize(15);
	printVector(v1); //如重新指定过长,默认用0填充,也可以指定,如 v1.resize(15, 100),则改为用100填充

	v1.resize(5);
	printVector(v1);  //如过短,则超出部分会被删除


}

int main()
{
	test01();

	system("pause");
	return 0;
}

vector插入和删除

功能描述:
对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(); //删除容器中所有元

示例:

#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;
	//尾插法
	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(30);
	v1.push_back(40);
	v1.push_back(50);
	printVector(v1);

	//尾删法
	v1.pop_back();
	printVector(v1);

	//插入 第一个参数是迭代器
	v1.insert(v1.begin(), 100);
	printVector(v1);

	v1.insert(v1.begin(), 2, 500);
	printVector(v1);

	//删除
	v1.erase(v1.begin());
	printVector(v1);

	//清空 和v1.clear()等效
	v1.erase(v1.begin(), v1.end());
	printVector(v1);

}

int main()
{
	test01();

	system("pause");
	return 0;
}

vector数据存取

功能描述:
对vector中的数据的存取操作
函数原型:

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

示例:

#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);
	}
	
	//利用[]方式来访问s数组中元素
	for (int i = 0; i < v1.size(); i++)
	{
		cout << v1[i] << " ";
	}
	cout << endl;

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

	//获取第一个元素
	cout << "第一个元素为:" << v1.front() << endl;

	//获取最后一个元素
	cout << "最后一个元素为:" << v1.back() << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

vector互换容器

功能描述:
实现两个容器内元素进行互换
函数原型:
swap(vec); // 将vec与本身的元素互换

示例:

#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;
	for (int i = 10; i > 0; i--)
	{
		v2.push_back(i);
	}
	printVector(v2);

	cout << "交换后" << endl;
	v1.swap(v2);
	printVector(v1);
	printVector(v2);
}

//实际用途
//巧用swap可以收缩内存空间
void test02()
{
	vector<int>v;
	for (int i = 0; i < 100000; i++)
	{
		v.push_back(i);
	}

	cout << "v的容量为:" << v.capacity() << endl;
	cout << "v的大小为:" << v.size() << endl;

	v.resize(3); //重新指定大小
	cout << "v的容量为:" << v.capacity() << endl;
	cout << "v的大小为:" << v.size() << endl;
	//运行结果大小变为3,容量没变,浪费空间
	//使用swap收缩
	vector<int>(v).swap(v); //相当于利用拷贝函数创建了一个匿名容器vector<int>(v)与原本的v交换了容器
	cout << "v的容量为:" << v.capacity() << endl;
	cout << "v的大小为:" << v.size() << endl;
}

int main()
{
	test01();
	test02();

	system("pause");
	return 0;
}

vector预留空间

功能描述:
减少vector在动态扩展容量时的扩展次数
函数原型:

  • reserve(int len); //容器预留len个元素长度,预留位置不初始化,元素不可访问。
    示例:
#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;
	int num = 0; //统计内存开辟次数
	int *p = NULL;
	for (int i = 0; i < 100000; i++)
	{
		v1.push_back(i);
		if (p != &v1[0])
		{
			p = &v1[0];
			num++;
		}
	}
	cout << "num=" << num << endl;
	cout << v1.capacity() << endl; //130000+


	//利用reserve预留空间
	vector<int>v2;
	v2.reserve(100000);
	int numV2 = 0;
	int *p_V2 = NULL;
	for (int i = 0; i < 10000; i++)
	{
		v2.push_back(i);
		if (p_V2 != &v2[0])
		{
			p_V2 = &v2[0];
			numV2++;
		}
	}
	cout << "numV2=" << numV2 << endl;
	cout << v2.capacity() << endl; //100000
	
}

int main()
{
	test01();

	system("pause");
	return 0;
}

string容器

string构造函数

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

/*
- string();  创建一个空的字符串 例如:string str
- string(const char* s);  使用字符串s初始化
- string(const string& str);  使用一个string对象初始化另一个string对象
- string(int n, char c);  使用n个字符c初始化
*/

void test01()
{
	string s1; //默认构造
	
	const char * str= "hello world";
	string s2(str); //使用字符串初始化
	cout << "s2=" << s2 << endl;

	string s3(s2); //使用一个string对象初始化另一个string对象
	cout << "s3=" << s3 << endl;

	string s4(10, 'a'); //使用n个字符c初始化
	cout << "s4=" << s4 << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

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的前几个字符赋给当前的字符串
  • string& assign(const string &s); 把字符串s赋给当前的字符串
  • string& assign(int n, char c); 把n个字符c赋给当前的字符串

示例:

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

/*
- 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的前几个字符赋给当前的字符串
- string& assign(const string &s);  把字符串s赋给当前的字符串
- string& assign(int n, char c);  把n个字符c赋给当前的字符串
*/

void test01()
{
	string str1;
	str1 = "hello world";
	cout << "str1=" << str1 << endl;

	string str2;
	str2 = str1;
	cout << "str2=" << str2 << endl;

	string str3;
	str3 = 'a';
	cout << "str3=" << str3 << endl;

	string str4;
	str4.assign("hello C++");
	cout << "str4=" << str4 << endl;

	string str5;
	str5.assign("hello C++", 8);
	cout << "str5=" << str5 << endl;

	string str6;
	str6.assign(str5);
	cout << "str6=" << str6 << endl;

	string str7;
	str7.assign(5, 'c');
	cout << "str7=" << str7 << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

string字符串拼接

函数原型:

  • string& operator+=(const char* str); 把字符串str连接到当前字符串结尾
  • string& operator+=(const char c); 把字符c连接到当前字符串结尾
  • string& operator+=(const string &s); 把字符串s连接到当前字符串结尾
  • string& append(const char* s); 把字符串s连接到当前字符串结尾
  • string& append(const char* s, int n); 把字符串s的前n个字符连接到当前字符串结尾
  • string& append(const string &s); 把字符串s连接到当前字符串结尾
  • string& append(const char* s, int pos, int n); 字符串s中从pos开始的n个字符连接到字符串结尾

示例:

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

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

void test01()
{
	string str1 = "我";
	str1 += "爱玩游戏";
	cout << "str1=" << str1 << endl;

	str1 += ":";
	cout << "str1=" << str1 << endl;

	string str2 = "LOL DNF";
	str1 += str2;
	cout << "str1=" << str1 << endl;
	
	string str3 = "I";
	str3.append(" love ");
	cout << "str3=" << str3 << endl;

	str3.append("game abcde", 5);
	cout << "str3=" << str3 << endl;

	str3.append(str2);
	cout << "str3=" << str3 << endl;

	str3.append(str2, 0, 3);
	cout << "str3=" << str3 << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

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
#include <iostream>
#include <string>
using namespace std;

/*
- 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()
{
	string str1 = "abcdefg";
	int pos = str1.find("de");
	if (pos == -1)
	{
		cout << "未找到" << endl;
	}
	else
	{
		cout << "pos=" << pos << endl;
	}

	//rfind
	pos = str1.rfind("d");
	cout << "pos=" << pos << endl;  //和find结果相同,只是从右开始查找的第一个位置

}

//替换
void test02()
{
	string str1 = "abcdefg";
	str1.replace(1, 3, "1111"); //从1号位置起,3个字符替换为1111,即结果为a1111efg
	cout << "str1=" << str1 << endl;
}

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

string字符串比较

功能描述:
字符串之间的比较
比较方式:
字符串比较是按字符的ASCII码进行对比
= 返回 0
> 返回 1
< 返回 -1
函数原型:

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

示例:

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

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

void test01()
{
	string str1 = "hello";
	string str2 = "xello";
	if (str1.compare(str2) == 0)
	{
		cout << "str1=str2" << endl;
	}
	else if (str1.compare(str2) > 0)
	{
		cout << "str1>str2" << endl;
	}
	else
	{
		cout << "str1<str2" << endl;
	}

}

int main()
{
	test01();

	system("pause");
	return 0;
}

string字符存取

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

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

示例:

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

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

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

	//1.通过[]方式取字符
	for (int i = 0; i < str.size(); i++)
	{
		cout << str[i] << " ";
	}
	cout << endl;

	//2.通过at方法获取字符
	for (int i = 0; i < str.size(); i++)
	{
		cout << str.at(i) << " ";
	}
	cout << endl;

	//修改单个字符
	str[0] = 'x';
	cout << "str=" << str << endl;

	str.at(1) = 'x';
	cout << "str=" << str << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

string插入和删除

功能描述:
对string字符串进行插入和删除字符操作

函数原型:

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

示例:

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

/*
- 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";

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

	//删除
	str.erase(1, 3);
	cout << "str=" << str << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

string子串

功能描述:
从字符串中获取想要的子串

函数原型:

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

示例:

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

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

//string 求子串
void test01()
{
	string str = "abcdef";
	string subStr = str.substr(1, 3);
	cout << "subStr=" << subStr << endl;


}

//实用操作
void test02()
{
	string email = "[email protected]";
	//从邮件地址中获取信息
	int pos = email.find('@');
	string userName = email.substr(0, pos);
	cout << "userName=" << userName << endl;
}

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

deque容器

deque容器基本概念

功能:
双端数组,可以对头端进行插入删除操作
deque与vector区别:

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

在这里插入图片描述
deque内部工作原理:
deque内部有个中控器,维护每段缓冲区中的内容,缓冲区中存放真实数据
中控器维护的是每个缓冲区的地址,使得使用deque时像一片连续的内存空间
在这里插入图片描述
deque容器的迭代器也是支持随机访问的

deque构造函数

功能描述:
deque容器构造
函数原型:
deque deqT; //默认构造形式
deque(beg, end); //构造函数将[beg, end)区间中的元素拷贝给本身。
deque(n, elem); //构造函数将n个elem拷贝给本身。
deque(const deque &deq); //拷贝构造函数
示例:

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

void printDeque(const deque<int>&d) //传入const防止被修改,下方迭代器相应改为const_iterator
{
	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}


//deque构造函数
void test01()
{
	deque<int>d1;
	for (int i = 0; i < 10; i++)
	{
		d1.push_back(i);
	}
	printDeque(d1);

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

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

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

int main()
{
	test01();

	system("pause");
	return 0;
}

deque赋值操作

功能描述:
给deque容器进行赋值
函数原型:

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

示例:

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

void printDeque(const deque<int>&d) //传入const防止被修改,下方迭代器相应改为const_iterator
{
	for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}


//deque构造函数
void test01()
{
	deque<int>d1;
	for (int i = 0; i < 10; i++)
	{
		d1.push_back(i);
	}
	printDeque(d1);

	//operator=赋值
	deque<int>d2 = d1;
	printDeque(d2);

	//assign
	deque<int>d3;
	d3.assign(d1.begin(), d1.end());
	printDeque(d3);

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

int main()
{
	test01();

	system("pause");
	return 0;
}

deque大小操作

功能描述:
对deque容器的大小进行操作
函数原型:

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

示例:

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

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


//deque容器大小操作
void test01()
{
	deque<int>d1;
	for (int i = 0; i < 10; i++)
	{
		d1.push_back(i);
	}
	printDeque(d1);

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

	//重新指定大小
	d1.resize(15);
	printDeque(d1);
	d1.resize(20, 1);
	printDeque(d1);
	d1.resize(5);
	printDeque(d1);
}

int main()
{
	test01();

	system("pause");
	return 0;
}

deque 插入和删除

功能描述:
向deque容器中插入和删除数据
函数原型:
两端插入操作:

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

指定位置操作:

  • insert(pos,elem); //在pos位置插入一个elem元素的拷贝,返回新数据的位置。
  • insert(pos,n,elem); //在pos位置插入n个elem数据,无返回值。
  • insert(pos,beg,end); //在pos位置插入[beg,end)区间的数据,无返回值。
    clear(); //清空容器的所有数据
  • erase(beg,end); //删除[beg,end)区间的数据,返回下一个数据的位置。
  • erase(pos); //删除pos位置的数据,返回下一个数据的位置。

示例:

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

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


//两端增删
void test01()
{
	deque<int>d1;
	//尾插
	d1.push_back(10);
	d1.push_back(20);

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

	//尾删
	d1.pop_back();
	printDeque(d1);
	
	//头删
	d1.pop_front();
	printDeque(d1);	
}

//指定插入
void test02()
{
	deque<int>d1;
	//尾插
	d1.push_back(10);
	d1.push_back(20);

	//头插
	d1.push_front(100);
	d1.push_front(200);
	printDeque(d1);  //200 100 10 20

	//insert插入
	d1.insert(d1.begin(), 1000); //1000 200 10 20
	d1.insert(d1.begin(), 2, 10000); //10000 10000 1000 200 10 20

	//按照区间插入
	deque<int>d2;
	d2.push_back(1);
	d2.push_back(2);
	d2.push_back(3);

	d1.insert(d1.begin(), d2.begin(), d2.end()); //1 2 3 10000 10000 1000 200 100 10 20
	printDeque(d1);
}

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

	//头插
	d1.push_front(100);
	d1.push_front(200);
	printDeque(d1);  //200 100 10 20

	//删除
	d1.erase(d1.begin());
	printDeque(d1);

	//按照区间删除
	d1.erase(d1.begin(), d1.end()); //清空 与d1.clear()等效
}

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

deque 数据存取

功能描述:
对deque 中的数据的存取操作
函数原型:

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

示例:

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

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

//deque容器数据存取
void test01()
{
	deque<int>d1;
	d1.push_back(10);
	d1.push_back(20);
	d1.push_back(30);
	d1.push_front(100);
	d1.push_front(200);
	d1.push_front(300);

	//通过[]访问元素
	for (int i = 0; i < d1.size(); i++)
	{
		cout << d1[i] << " ";
	}
	cout << endl;
	
	//通过at访问元素
	for (int i = 0; i < d1.size(); i++)
	{
		cout << d1.at(i) << " ";
	}
	cout << endl;

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

int main()
{
	test01();

	system("pause");
	return 0;
}

deque 排序

功能描述:
利用算法实现对deque容器进行排序
算法:

  • sort(iterator beg, iterator end) //对beg和end区间内元素进行排序

示例:
评委打分项目

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

class Player
{
public:
	Player(string name, int score)
	{
		this->m_Name = name;
		this->m_score = score;
	}

	string m_Name;
	int m_score;
};

void creatPersongVector(vector<Player> &v)
{
	string name_seed = "ABCDE";
	int score = 0;
	for (int i = 0; i < name_seed.size(); i++)
	{
		string name = "选手";
		name += name_seed[i];
		Player p(name, score);
		v.push_back(p);
	}
}

void setScore(vector<Player>&v)
{
	for (vector<Player>::iterator it = v.begin(); it != v.end(); it++)
	{
		deque<int> d;
		for (int i = 0; i < 10; i++)
		{
			int score = rand() % 40 + 61;
			d.push_back(score);
		}
		sort(d.begin(), d.end());
		d.pop_back();
		d.pop_front();
		int sum = 0;
		for (int i = 0; i < d.size(); i++)
		{
			sum += d[i];
		}
		int avg = sum / d.size();
		it->m_score = avg;
	}
}

int main()
{
	srand((unsigned int)time(NULL));
	vector<Player>v;
	creatPersongVector(v);
	setScore(v);

	for (vector<Player>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << "姓名:" << it->m_Name << "\t分数:" << it->m_score << endl;
	}

	system("pause");
	return 0;
}

stack容器

stack 基本概念

概念: stack是一种先进后出(First In Last Out,FILO)的数据结构,它只有一个出口
在这里插入图片描述
栈中只有顶端的元素才可以被外界使用,因此栈不允许有遍历行为
栈中进入数据称为 — 入栈 push
栈中弹出数据称为 — 出栈 pop

stack 常用接口

功能描述: 栈容器常用的对外接口
构造函数:

  • stack stk; //stack采用模板类实现, stack对象的默认构造形式
  • stack(const stack &stk); //拷贝构造函数
    赋值操作:
  • stack& operator=(const stack &stk); //重载等号操作符
    数据存取:
  • push(elem); //向栈顶添加元素
  • pop(); //从栈顶移除第一个元素
  • top(); //返回栈顶元素
    大小操作:
  • empty(); //判断堆栈是否为空
  • size(); //返回栈的大小

示例:

#include <iostream>
#include <string>
#include <stack>

using namespace std;

//栈stack容器

void test01()
{
	//特点:符合先进后出的数据结构
	stack<int>s;

	//入栈
	s.push(10);
	s.push(20);
	s.push(30);
	s.push(40);

	cout << "栈的大小:" << s.size() << endl;

	//只要栈不为空就查看栈顶,并执行出栈操作
	while (!s.empty())
	{
		//查看栈顶元素
		cout << "栈顶元素为:" << s.top() << endl;

		//出栈
		s.pop();
	}

	cout << "栈的大小:" << s.size() << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

queue 容器

queue 基本概念

概念: Queue是一种先进先出(First In First Out,FIFO)的数据结构,它有两个出口
在这里插入图片描述
队列容器允许从一端新增元素,从另一端移除元素
队列中只有队头和队尾才可以被外界使用,因此队列不允许有遍历行为
队列中进数据称为 — 入队 push
队列中出数据称为 — 出队 pop

queue 常用接口

功能描述: 栈容器常用的对外接口
构造函数:

  • queue que; //queue采用模板类实现,queue对象的默认构造形式
  • queue(const queue &que); //拷贝构造函数
    赋值操作:
  • queue& operator=(const queue &que); //重载等号操作符
    数据存取:
  • push(elem); //往队尾添加元素
  • pop(); //从队头移除第一个元素
  • back(); //返回最后一个元素
  • front(); //返回第一个元素
    大小操作:
  • empty(); //判断堆栈是否为空
  • size(); //返回栈的大小
    示例:
#include <iostream>
#include <string>
#include <queue>

using namespace std;

//队列 Queue

class Person
{
public:
	Person(string name, int age) 
	{
		this->m_name = name;
		this->m_age = age;
	}
	string m_name;
	int m_age;
};

void test01()
{
	//创建队列
	queue<Person>q;

	//准备数据
	Person p1("唐僧", 30);
	Person p2("孙悟空", 300);
	Person p3("猪八戒", 360);
	Person p4("沙悟净", 380);

	//入队
	q.push(p1);
	q.push(p2);
	q.push(p3);
	q.push(p4);
	
	cout << "队列大小为:" << q.size() << endl;

	//判断只要队列不为空,查看队头队尾,出队
	while (!q.empty())
	{
		//查看队头
		cout << "队头为:" << q.front().m_name << endl;
		//查看队尾
		cout << "队尾为:" << q.front().m_age << endl;
		//出队
		q.pop();
	}
	cout << "队列大小为:" << q.size() << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

list容器

list基本概念

功能: 将数据进行链式存储
链表(list)是一种物理存储单元上非连续的存储结构,数据元素的逻辑顺序是通过链表中的指针链接实现的
链表的组成:链表由一系列结点组成
结点的组成:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域
STL中的链表是一个双向循环链表
在这里插入图片描述
由于链表的存储方式并不是连续的内存空间,因此链表list中的迭代器只支持前移和后移,属于双向迭代器
list的优点:
采用动态存储分配,不会造成内存浪费和溢出
链表执行插入和删除操作十分方便,修改指针即可,不需要移动大量元素
list的缺点:
链表灵活,但是空间(指针域) 和 时间(遍历)额外耗费较大
List有一个重要的性质,插入操作和删除操作都不会造成原有list迭代器的失效,这在vector是不成立的。
总结: STL中List和vector是两个最常被使用的容器,各有优缺点

list构造函数

功能描述:
创建list容器
函数原型:

  • list lst; //list采用采用模板类实现,对象的默认构造形式:
  • list(beg,end); //构造函数将[beg, end)区间中的元素拷贝给本身。
  • list(n,elem); //构造函数将n个elem拷贝给本身。
  • list(const list &lst); //拷贝构造函数。
    示例:
#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;
}

void test01()
{
	//创建list容器
	list<int>l1;
	
	//添加数据
	l1.push_back(10);
	l1.push_back(20);
	l1.push_back(30);
	l1.push_back(40);

	//遍历容器
	printList(l1);

	//区间方式构造
	list<int>l2(l1.begin(), l1.end());
	printList(l2);

	//拷贝构造
	list<int>l3(l2);
	printList(l3);

	//n个elem
	list<int>l4(10, 1000);
	printList(l4);


}


int main()
{
	test01();

	system("pause");
	return 0;
}

list 赋值和交换

功能描述:
给list容器进行赋值,以及交换list容器
函数原型:

  • assign(beg, end); //将[beg, end)区间中的数据拷贝赋值给本身。
  • assign(n, elem); //将n个elem拷贝赋值给本身。
  • list& operator=(const list &lst); //重载等号操作符
  • swap(lst); //将lst与本身的元素互换。
    示例:
#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赋值和交换
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;
	printList(l2);

	list<int>l3;
	l3.assign(l2.begin(), l2.end());
	printList(l3);

	list<int>l4;
	l4.assign(10, 100);
	printList(l4);
}

//交换
void test02()
{
	list<int>l1;
	l1.push_back(10);
	l1.push_back(20);
	l1.push_back(30);
	l1.push_back(40);

	list<int>l2;
	l2.assign(10, 100);

	cout << "交换前 " << endl;
	printList(l1);
	printList(l2);

	l1.swap(l2);
	cout << "交换后 " << endl;
	printList(l1);
	printList(l2);
}

int main()
{
	test01();
	test02();

	system("pause");
	return 0;
}

list 大小操作

功能描述:
对list容器的大小进行操作
函数原型:

  • size(); //返回容器中元素的个数
  • empty(); //判断容器是否为空
  • resize(num); //重新指定容器的长度为num,若容器变长,则以默认值填充新位置。//如果容器变短,则末尾超出容器长度的元素被删除。
  • resize(num, elem); //重新指定容器的长度为num,若容器变长,则以elem值填充新位置。//如果容器变短,则末尾超出容器长度的元素被删除。
    示例:
#include <iostream>
#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赋值和交换
void test01()
{
	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容器大小为:" << l1.size() << endl;
		printList(l1);
	}

	//重新指定大小
	l1.resize(10);
	printList(l1);

	l1.resize(2);
	printList(l1);
}


int main()
{
	test01();

	system("pause");
	return 0;
}

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();//移除容器的所有数据
  • erase(beg,end);//删除[beg,end)区间的数据,返回下一个数据的位置。
  • erase(pos);//删除pos位置的数据,返回下一个数据的位置。
  • remove(elem);//删除容器中所有与elem值匹配的元素。
    示例:
#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插入和删除
void test01()
{
	list<int>l1;
	//尾插
	l1.push_back(10);
	l1.push_back(20);
	l1.push_back(30);
	l1.push_back(40);

	//头插
	l1.push_front(100);
	l1.push_front(200);
	l1.push_front(300);

	printList(l1);

	//尾删法
	l1.pop_back();
	printList(l1);

	//头删法
	l1.pop_front();
	printList(l1);

	//insert插入
	list<int>::iterator it = l1.begin();
	l1.insert(++it, 1000);
	printList(l1);

	//删除
	it = l1.begin();
	l1.erase(++it);
	printList(l1);

	//移除
	l1.push_back(10000);
	l1.push_back(10000);
	l1.push_back(10000);
	l1.push_back(10000);
	printList(l1);
	l1.remove(10000);
	printList(l1);

	//清空
	l1.clear();
	printList(l1);
}

int main()
{
	test01();

	system("pause");
	return 0;
}

list 数据存取

功能描述:
对list容器中数据进行存取
函数原型:

  • front(); //返回第一个元素。
  • back(); //返回最后一个元素。
    示例:
#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数据存取
void test01()
{
	list<int>l1;
	//尾插
	l1.push_back(10);
	l1.push_back(20);
	l1.push_back(30);
	l1.push_back(40);

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

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

int main()
{
	test01();

	system("pause");
	return 0;
}

list 反转和排序

功能描述:
将容器中的元素反转,以及将容器中的数据进行排序
函数原型:

  • reverse(); //反转链表
  • sort(); //链表排序
    示例:
#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;
}

bool myCompare(int v1, int v2)
{
	//降序就让第一个数大于第二个数
	return v1 > v2;
}

//list反转和排序
void test01()
{
	list<int>l1;
	//尾插
	l1.push_back(50);
	l1.push_back(20);
	l1.push_back(60);
	l1.push_back(40);
	l1.push_back(30);
	printList(l1);

	//反转
	l1.reverse();
	printList(l1);

	//排序
	l1.sort(); //默认升序排序
	printList(l1);
	//降序排列
	l1.sort(myCompare);
	printList(l1);
}

int main()
{
	test01();

	system("pause");
	return 0;
}

排序案例

案例描述: 将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高
排序规则: 按照年龄进行升序,如果年龄相同按照身高进行降序
示例:

#include <iostream>
#include <string>
#include <list>

using namespace std;

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

void printInfo(const list<Person> &l)
{
	for (list<Person>::const_iterator it = l.begin(); it != l.end(); it++)
	{
		cout << "姓名:" << (*it).m_name << "\t年龄:" << it->m_age << "\t身高:" << it->m_height << endl;
	}
}

//指定排序规则
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);

	printInfo(l);

	//排序后
	cout << string(20, '*') << endl;
	l.sort(comparePerson);
	printInfo(l);
}

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

set/ multiset 容器

set基本概念

简介:
所有元素都会在插入时自动被排序
本质:
set/multiset属于关联式容器,底层结构是用二叉树实现。
set和multiset区别:
set不允许容器中有重复的元素
multiset允许容器中有重复的元素

set构造和赋值

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

  • set st; //默认构造函数:
  • set(const set &st); //拷贝构造函数
    赋值:
  • set& operator=(const set &st); //重载等号操作符
    示例:
#include <iostream>
#include <string>
#include <set>

using namespace std;

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

void test01()
{
	set<int>s1;

	//插入数据只有insert方式
	s1.insert(10);
	s1.insert(40);
	s1.insert(30);
	s1.insert(20);
	s1.insert(30);

	//遍历容器
	//set容器特点:所有元素在插入时会被自动排序
	//set容器不允许插入重复的值
	printSet(s1);

	//拷贝构造
	set<int>s2(s1);
	printSet(s2);

	//赋值
	set<int>s3;
	s3 = s2;
	printSet(s3);
}

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

set大小和交换

功能描述:
统计set容器大小以及交换set容器
函数原型:

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

using namespace std;

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

void test01()
{
	set<int>s1;
	s1.insert(10);
	s1.insert(40);
	s1.insert(30);
	s1.insert(20);
	
	//判断是否为空
	if (s1.empty())
	{
		cout << "s1为空" << endl;
	}
	else
	{
		printSet(s1);
		cout << "s1大小为:" << s1.size() << endl;
	}

	set<int>s2;
	s2.insert(50);
	s2.insert(800);
	s2.insert(60);
	s2.insert(350);

	printSet(s2);

	s1.swap(s2);
	cout << "交换后" << endl;
	printSet(s1);
	printSet(s2);
	
}

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

set插入和删除

功能描述:
set容器进行插入数据和删除数据
函数原型:

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

using namespace std;

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

void test01()
{
	set<int>s1;
	s1.insert(50);
	s1.insert(40);
	s1.insert(30);
	s1.insert(20);
	
	printSet(s1);

	//删除
	s1.erase(s1.begin());
	printSet(s1);
	
	//删除的重载版本
	s1.erase(30);
	printSet(s1);

	//清空
	s1.clear();  //也可以用s1.erase(s1.begin(), s1.end())
	printSet(s1);
}

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

set查找和统计

功能描述:
对set容器进行查找数据以及统计数据
函数原型:

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

示例:

#include <iostream>
#include <string>
#include <set>

using namespace std;

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

void test01()
{
	set<int>s1;
	s1.insert(50);
	s1.insert(40);
	s1.insert(30);
	s1.insert(20);
	
	//查找
	set<int>::iterator pos = s1.find(30);

	if (pos != s1.end())
	{
		cout << "找到元素" << endl;

	}
	else
	{
		cout << "未找到元素" << endl;
	}

	//统计
	int num = s1.count(30);
	cout << num << endl;
}

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

set和multiset区别

学习目标:
掌握set和multiset的区别
区别:
set不可以插入重复数据,而multiset可以
set插入数据的同时会返回插入结果,表示插入是否成功
multiset不会检测数据,因此可以插入重复数据

示例:

#include <iostream>
#include <string>
#include <set>

using namespace std;

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

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

	//multiset允许插入重复值
	multiset<int> s2;
	s2.insert(10);
	s2.insert(10);
	for (multiset<int>::iterator it = s2.begin(); it != s2.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}

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

pair对组创建

功能描述:
成对出现的数据,利用对组可以返回两个数据
两种创建方式:

  • pair<type, type> p ( value1, value2 );
  • pair<type, type> p = make_pair( value1, value2 );
    示例:
#include <iostream>
#include <string>

using namespace std;

void test01()
{
	//第一种方式
	pair<string, int>p("Tom", 20);
	cout << "姓名:" << p.first << "\t年龄:" << p.second << endl;

	//第二种方式
	pair<string, int>p2 = make_pair("Jerry", 30);
	cout << "姓名:" << p2.first << "\t年龄:" << p2.second << endl;
}

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

set容器排序

学习目标:
set容器默认排序规则为从小到大,掌握如何改变排序规则
主要技术点:
利用仿函数,可以改变排序规则
示例一
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;
}

class MyCompare
{
public:
   bool operator()(int v1, int v2)
   {
   	return v1 > v2;
   }
};

//set容器排序
void test01()
{
   set<int>s1;
   s1.insert(30);
   s1.insert(10);
   s1.insert(50);
   s1.insert(40);
   s1.insert(60);
   printSet(s1);

   //指定排序规则为从大到小
   set<int, MyCompare>s2;
   s2.insert(30);
   s2.insert(10);
   s2.insert(50);
   s2.insert(40);
   s2.insert(60);
   for (set<int>::const_iterator it = s2.begin(); it != s2.end() ;it++)
   {
   	cout << *it << " ";
   }
   cout << endl;
   
}

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

示例二
set存放自定义数据类型

#include <iostream>
#include <string>
#include <set>

using namespace std;

class Person
{
public:
	Person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}

	string m_name;
	int m_age;
};

class MyCompare
{
public:
	bool operator()(const Person p1, const Person p2)
	{
		//按照年龄降序
		return p1.m_age > p2.m_age;
	}
};

//set容器排序
void test01()
{
	set<Person, MyCompare>s;
	Person p1("刘备", 23); 
	Person p2("关羽", 27); 
	Person p3("张飞", 25); 
	Person p4("赵云", 21);

	s.insert(p1);
	s.insert(p2);
	s.insert(p3);
	s.insert(p4);
	for (set<Person, MyCompare>::const_iterator it = s.begin(); it != s.end(); it++)
	{
		cout << "姓名:" << it->m_name << "\t年龄:" << it->m_age << endl;
	}
}

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

map/ multimap容器

map基本概念

简介:
map中所有元素都是pair
pair中第一个元素为key(键值),起到索引作用,第二个元素为value(实值)
所有元素都会根据元素的键值自动排序
本质:
map/multimap属于关联式容器,底层结构是用二叉树实现。
优点:
可以根据key值快速找到value值
map和multimap区别:
map不允许容器中有重复key值元素
multimap允许容器中有重复key值元素

3.9.2 map构造和赋值

功能描述:
对map容器进行构造和赋值操作
函数原型:
构造:

  • map<T1, T2> mp; //map默认构造函数: map(const map &mp); //拷贝构造函数
    赋值:
  • map& operator=(const map &mp); //重载等号操作符
    示例:
#include <iostream>
#include <string>
#include <map>

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 << "\tvalue=" << it->second << endl;
	}
	cout << endl;
}

void test01()
{
	//创建map容器
	map<int, int>m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(3, 30));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(4, 40));
	m.insert(pair<int, int>(5, 50));
	printMap(m);

	//拷贝构造
	map<int, int>m2(m);
	printMap(m2);

	//赋值
	map<int, int>m3 = m2;
	printMap(m3);
}

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

map大小和交换

功能描述:
统计map容器大小以及交换map容器
函数原型:

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

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 << "\tvalue=" << it->second << endl;
	}
	cout << endl;
}

void test01()
{
	//创建map容器
	map<int, int>m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(3, 30));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(4, 40));
	m.insert(pair<int, int>(5, 50));
	
	if (m.empty())
	{
		cout << "容器为空" << endl;
	}
	else
	{
		printMap(m);
		cout << "容器大小为:" << m.size() << endl;
	}

	//交换
	map<int, int>m2;
	m2.insert(pair<int, int>(10, 10));
	m2.insert(pair<int, int>(13, 30));
	m2.insert(pair<int, int>(12, 20));
	m2.insert(pair<int, int>(14, 40));
	m2.insert(pair<int, int>(15, 50));
	printMap(m2);

	m.swap(m2);
	cout << "交换后" << endl;
	printMap(m);
	printMap(m2);
}

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

map插入和删除

功能描述:
map容器进行插入数据和删除数据
函数原型:

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

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 << "\tvalue=" << it->second << endl;
	}
	cout << endl;
}

void test01()
{
	//创建map容器
	map<int, int>m;
	//插入
	//第一种
	m.insert(pair<int, int>(1, 10));
	//第二种
	m.insert(make_pair(7, 56));
	//第三种
	m.insert(map<int, int>::value_type(3, 30));
	//第四种 不建议 如果原本不存在 打印时会自动创建键值对,主要用于通过key访问value
	m[4] = 40;

	printMap(m);

	//删除
	m.erase(m.begin());
	printMap(m);
	m.erase(3); //按照key删除
	printMap(m);
	m.erase(m.begin(), m.end());
	printMap(m);	//等效m.clear()
}

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

map查找和统计

功能描述:
对map容器进行查找数据以及统计数据
函数原型:
find(key); //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();
count(key); //统计key的元素个数
示例:

#include <iostream>
#include <string>
#include <map>

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 << "\tvalue=" << it->second << endl;
	}
	cout << endl;
}

void test01()
{
	//创建map容器
	map<int, int>m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(3, 30));
	
	map<int, int>::iterator pos = m.find(3);
	if (pos != m.end())
	{
		cout << "找到元素" << endl;
		cout << "key=" << pos->first << "\tvalue=" << pos->second << endl;
	}
	else
	{
		cout << "未找到" << endl;
	}

	int num = m.count(3);
	cout << num << endl;
}

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

map容器排序

学习目标:
map容器默认排序规则为 按照key值进行 从小到大排序,掌握如何改变排序规则
主要技术点:
利用仿函数,可以改变排序规则
示例:

#include <iostream>
#include <string>
#include <map>

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 << "\tvalue=" << it->second << endl;
	}
	cout << endl;
}

class myCompare
{
public:
	bool operator()(int v1, int v2)
	{
		return v1 > v2;
	}
};


void test01()
{
	//创建map容器
	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>(5, 50));
	m.insert(pair<int, int>(4, 40));
	for (map<int, int, myCompare>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << "key=" << it->first << "\tvalue=" << it->second << endl;
	}
	cout << endl;
}

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

案例-员工分组

案例描述

公司今天招聘了10个员工(ABCDEFGHIJ),10名员工进入公司之后,需要指派员工在那个部门工作
员工信息有: 姓名 工资组成;部门分为:策划、美术、研发
随机给10名员工分配部门和工资
通过multimap进行信息的插入 key(部门编号) value(员工)
分部门显示员工信息

实现步骤

  1. 创建10名员工,放到vector中
  2. 遍历vector容器,取出每个员工,进行随机分组
  3. 分组后,将员工部门编号作为key,具体员工作为value,放入到multimap容器中
  4. 分部门显示员工信息

12
案例代码:

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <ctime>

using namespace std;

#define CEHUA 0
#define MEISHU 1
#define YANFA 2

class Worker
{
public:
	string m_name;
	int m_Salary;
};

void createWorker(vector<Worker> &v)
{
	string nameSeed="ABCDEFGHIJ";
	for (int i = 0; i < nameSeed.size(); i++)
	{
		Worker worker;
		worker.m_name = "员工";
		worker.m_name += nameSeed[i];
		worker.m_Salary = rand() % 10000 + 10000;
		v.push_back(worker);
	}
}

void setGroup(vector<Worker> &v, multimap<int, Worker> &m)
{
	for (vector<Worker>::iterator it = v.begin(); it != v.end(); it++)
	{
		int deptID = rand() % 3;
		m.insert(make_pair(deptID, *it));
	}
}

void showWorkerByGroup(multimap<int, Worker> &m)
{
	cout << "策划部门:" << endl;
	multimap<int, Worker>::iterator pos = m.find(CEHUA);
	int count = m.count(CEHUA); //统计策划部门总人数
	int index = 0;
	for (; pos != m.end() && index < count; pos++, index++)
	{
		cout << "姓名:" << pos->second.m_name << "\t工资:" << pos->second.m_Salary << endl;
	}
	cout << string(20, '-') << 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 << "\t工资:" << pos->second.m_Salary << endl;
	}
	cout << string(20, '-') << 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 << "\t工资:" << pos->second.m_Salary << endl;
	}
}

int main()
{
	vector<Worker>v_Worker;
	createWorker(v_Worker);

	//员工分组
	multimap<int, Worker>m_Worker;
	setGroup(v_Worker, m_Worker);

	//分组显示员工
	showWorkerByGroup(m_Worker);

	system("pause");
	return 0;
}

STL- 函数对象

函数对象概念

概念:
重载函数调用操作符的类,其对象常称为函数对象
函数对象使用重载的()时,行为类似函数调用,也叫仿函数
本质:
函数对象(仿函数)是一个类,不是一个函数

函数对象使用

特点:
函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
函数对象超出普通函数的概念,函数对象可以有自己的状态
函数对象可以作为参数传递

示例:

#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("Hello World");
	myPrint("Hello World");
	myPrint("Hello World");
	cout << "myPrint调用次数为:" << myPrint.count << endl;
}

void doPrint(MyPrint &mp, string test)
{
	mp(test);
}

//作为参数传递
void test03()
{
	MyPrint myPrint;
	doPrint(myPrint, "Hello c++");

}

int main()
{
	test01();
	test02();
	test03();

	system("pause");
	return 0;
}

谓词

谓词概念

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

一元谓词

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class GreaterFive
{
public:
	bool operator()(int val)
	{
		return val > 5;
	}
};

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

	//查找容器中有没有大于5的数字
	//GreaterFive()为匿名函数对象
	vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
	if (it == v.end())
	{
		cout << "未找到" << endl;
	}
	else
	{
		cout << "找到,数字为:" << *it << endl;
	}
}

int main()
{
	test01();

	system("pause");
	return 0;
}

二元谓词

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class MySort
{
public:
	bool operator()(int v1, int v2)
	{
		return v1 > v2;
	}
};

//二元谓词
void test01()
{
	vector<int>v;
	v.push_back(10);
	v.push_back(40);
	v.push_back(20);
	v.push_back(30);
	v.push_back(50);

	sort(v.begin(), v.end());

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

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

int main()
{
	test01();

	system("pause");
	return 0;
}

内建函数对象

内建函数对象意义

概念:
STL内建了一些函数对象
分类:

  • 算术仿函数
  • 关系仿函数
  • 逻辑仿函数
    用法:
  • 这些仿函数所产生的对象,用法和一般函数完全相同
  • 使用内建函数对象,需要引入头文件 #include

算术仿函数

功能描述:
实现四则运算
其中negate是一元运算,其他都是二元运算
仿函数原型:

  • template T plus //加法仿函数
  • template T minus //减法仿函数
  • template T multiplies //乘法仿函数
  • template T divides //除法仿函数
  • template T modulus //取模仿函数
  • template T negate //取反仿函数

示例:

#include <iostream>
#include <string>
#include <functional>

using namespace std;

//negate 一元仿函数  取反仿函数
void test01()
{
	negate<int>n;
	cout << n(50) << endl;
}
//plus 二元仿函数
void test02()
{
	plus<int>p;
	cout << p(10, 20) << endl;
}

int main()
{
	test01();
	test02();

	system("pause");
	return 0;
}

关系仿函数

功能描述:
实现关系对比
仿函数原型:

  • template bool equal_to //等于
  • template bool not_equal_to //不等于
  • template bool greater //大于
  • template bool greater_equal //大于等于
  • template bool less //小于
  • template bool less_equal //小于等于

示例:

#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <algorithm>

using namespace std;

//关系仿函数 大于 greater
void test01()
{
	vector<int>v;

	v.push_back(10);
	v.push_back(30);
	v.push_back(20);
	v.push_back(50);
	v.push_back(40);

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

	//降序
	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;
}

逻辑仿函数

功能描述:
实现逻辑运算
函数原型:

  • template bool logical_and //逻辑与
  • template bool logical_or //逻辑或
  • template bool logical_not //逻辑非

示例:

#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <algorithm>

using namespace std;

//逻辑仿函数 非 logical_not
void test01()
{
	vector<bool>v;

	v.push_back(true);
	v.push_back(false);
	v.push_back(true);
	v.push_back(false);
	v.push_back(true);

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

	//利用逻辑非将v搬运到另一个容器,并执行取反操作
	vector<bool>v2;
	v2.resize(v.size()); //使用transform搬运必须提前预留空间,否则报错
	transform(v.begin(), v.end(), v2.begin(), logical_not<bool>());
	for (vector<bool>::iterator it = v2.begin(); it != v2.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

STL- 常用算法

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

常用遍历算法

学习目标:
掌握常用的遍历算法
算法简介:
for_each //遍历容器
transform //搬运容器到另一个容器中

for_each

功能描述:
实现遍历容器
函数原型:

  • for_each(iterator beg, iterator end, _func);
    // 遍历算法 遍历容器元素
    // beg 开始迭代器
    // end 结束迭代器
    // _func 函数或者函数对象

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

//普通函数
void print01(int val)
{
	cout << val << endl;
}

//仿函数
class print02
{
public:
	void operator()(int value)
	{
		cout << value << endl;
	}
};

//for_each
void test01()
{
	vector<int>v;

	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	for_each(v.begin(), v.end(), print01);
	for_each(v.begin(), v.end(), print02());
}

int main()
{
	test01();

	system("pause");
	return 0;
}

transform

功能描述:
搬运容器到另一个容器中
函数原型:

  • transform(iterator beg1, iterator end1, iterator beg2, _func);
    //beg1 源容器开始迭代器
    //end1 源容器结束迭代器
    //beg2 目标容器开始迭代器
    //_func 函数或者函数对象

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class Transform
{
public:
	int operator()(int v)
	{
		return v+100;
	}
};

class MyPrint
{
public:
	void operator()(int val)
	{
		cout << val << endl;
	}
};

//for_each
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(), Transform());
	for_each(vtarget.begin(), vtarget.end(), MyPrint());
}

int main()
{
	test01();

	system("pause");
	return 0;
}

常用查找算法

学习目标:
掌握常用的查找算法
算法简介:

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

find

功能描述:
查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end()
函数原型:

  • find(iterator beg, iterator end, value);
    // 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
    // beg 开始迭代器
    // end 结束迭代器
    // value 查找的元素

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

//查找内置数据类型
void test01()
{
	vector<int>v;

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

	vector<int>::iterator it = find(v.begin(), v.end(), 5);
	if (it == v.end())
	{
		cout << "未找到" << endl;
	}
	else
	{
		cout << "找到" << *it << endl;
	}
}

class Person
{
public:
	Person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}

	//重载==号,让底层find知道如何对比Person数据类型
	bool operator==(const Person &p)
	{
		if (this->m_name == p.m_name && this->m_age == p.m_age)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	string m_name;
	int m_age;
};

//查找自定义数据类型
void test02()
{
	vector<Person>v;
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);

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

	vector<Person>::iterator it = find(v.begin(), v.end(), p2);
	if (it == v.end())
	{
		cout << "未找到" << endl;
	}
	else
	{
		cout << "找到" << it->m_name << endl;
	}
}

int main()
{
	test01();
	test02();

	system("pause");
	return 0;
}

find_if

功能描述:
按条件查找元素
函数原型:

  • find_if(iterator beg, iterator end, _Pred);
    // 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
    // beg 开始迭代器
    // end 结束迭代器
    // _Pred 函数或者谓词(返回bool类型的仿函数)

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class GreaterFive
{
public:
	bool operator()(int v)
	{
		return v > 5;
	}
};

//查找内置数据类型
void test01()
{
	vector<int>v;

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

	vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
	if (it == v.end())
	{
		cout << "未找到" << endl;
	}
	else
	{
		cout << "找到" << *it << endl;
	}
}

class Person
{
public:
	Person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}

	//重载==号,让底层find知道如何对比Person数据类型
	bool operator==(const Person &p)
	{
		if (this->m_name == p.m_name && this->m_age == p.m_age)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	string m_name;
	int m_age;
};

class Greater20
{
public:
	bool operator()(Person p)
	{
		return p.m_age>20;
	}
};

//查找自定义数据类型
void test02()
{
	vector<Person>v;
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);

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

	vector<Person>::iterator it = find_if(v.begin(), v.end(), Greater20());
	if (it == v.end())
	{
		cout << "未找到" << endl;
	}
	else
	{
		cout << "找到" << it->m_name << endl;
	}
}

int main()
{
	test01();
	test02();

	system("pause");
	return 0;
}

adjacent_find

功能描述:
查找相邻重复元素
函数原型:

  • adjacent_find(iterator beg, iterator end);
    // 查找相邻重复元素,返回相邻元素的第一个位置的迭代器
    // beg 开始迭代器
    // end 结束迭代器

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void test01()
{
	vector<int>v;
	v.push_back(0);
	v.push_back(2);
	v.push_back(1);
	v.push_back(6);
	v.push_back(3);
	v.push_back(3);
	v.push_back(5);
	v.push_back(3);

	vector<int>::iterator it = adjacent_find(v.begin(), v.end());
	if (it == v.end())
	{
		cout << "未找到" << endl;
	}
	else
	{
		cout << "找到" << *it << endl;
	}
}

int main()
{
	test01();

	system("pause");
	return 0;
}

binary_search

功能描述:
查找指定元素是否存在
函数原型:

  • bool binary_search(iterator beg, iterator end, value);
    // 查找指定的元素,查到 返回true 否则false
    // 注意: 在无序序列中不可用
    // beg 开始迭代器
    // end 结束迭代器
    // value 查找的元素

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void test01()
{
	vector<int>v;

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

	bool ret = binary_search(v.begin(), v.end(), 9);
	if (ret)
	{
		cout << "找到了" << endl;
	}
	else
	{
		cout << "未找到" << endl;
	}
}

int main()
{
	test01();

	system("pause");
	return 0;
}

count

功能描述:
统计元素个数
函数原型:

  • count(iterator beg, iterator end, value);
    // 统计元素出现次数
    // beg 开始迭代器
    // end 结束迭代器
    // value 统计的元素

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void test01()
{
	vector<int>v;

	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	v.push_back(30);
	v.push_back(50);
	v.push_back(40);
	v.push_back(40);

	int num = count(v.begin(), v.end(), 40);
	cout << num << endl;
}

class Person
{
public:
	Person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	bool operator==(const Person &p)
	{
		return this->m_name == p.m_name && this->m_age == p.m_age;
	}
	string m_name;
	int m_age;
};

void test02()
{
	vector<Person>v;
	Person p1("刘备", 35); 
	Person p2("关羽", 35); 
	Person p3("张飞", 35); 
	Person p4("赵云", 30); 
	Person p5("曹操", 25);
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4); 
	v.push_back(p5);

	Person p("诸葛亮", 27);
	int num = count(v.begin(), v.end(), p);
	cout << num << endl;
}

int main()
{
	test01();
	test02();

	system("pause");
	return 0;
}

count_if

功能描述:
按条件统计元素个数
函数原型:

  • count_if(iterator beg, iterator end, _Pred);
    // 按条件统计元素出现次数
    // beg 开始迭代器
    // end 结束迭代器
    // _Pred 谓词

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class Greater20
{
public:
	bool operator()(int val)
	{
		return val > 20;
	}
};

void test01()
{
	vector<int>v;

	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	v.push_back(30);
	v.push_back(50);
	v.push_back(40);
	v.push_back(40);

	int num = count_if(v.begin(), v.end(), Greater20());
	cout << num << endl;
}

class Person
{
public:
	Person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	
	string m_name;
	int m_age;
};

class Greater21
{
public:
	bool operator()(const Person &p)
	{
		return p.m_age > 20;
	}
};

void test02()
{
	vector<Person>v;
	Person p1("刘备", 35); 
	Person p2("关羽", 35); 
	Person p3("张飞", 35); 
	Person p4("赵云", 30); 
	Person p5("曹操", 25);
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4); 
	v.push_back(p5);

	Person p("诸葛亮", 27);
	int num = count_if(v.begin(), v.end(), Greater21());
	cout << num << endl;
}

int main()
{
	test01();
	test02();

	system("pause");
	return 0;
}

常用排序算法

学习目标:
掌握常用的排序算法
算法简介:

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

sort

功能描述:
对容器内元素进行排序
函数原型:

  • sort(iterator beg, iterator end, _Pred);
    // 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
    // beg 开始迭代器
    // end 结束迭代器
    // _Pred 谓词

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void MyPrint(int val)
{
	cout << val << " ";
}

void test01()
{
	vector<int>v;

	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	v.push_back(30);
	v.push_back(50);
	v.push_back(40);
	v.push_back(10);

	sort(v.begin(), v.end());
	for_each(v.begin(), v.end(), MyPrint);
	cout << endl;

	//改变为降序
	sort(v.begin(), v.end(), greater<int>());
	for_each(v.begin(), v.end(), MyPrint);
	cout << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

random_shuffle

功能描述:
洗牌 指定范围内的元素随机调整次序
函数原型:

  • random_shuffle(iterator beg, iterator end);
    // 指定范围内的元素随机调整次序
    // beg 开始迭代器
    // end 结束迭代器

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>

using namespace std;

void MyPrint(int val)
{
	cout << val << " ";
}

void test01()
{
	srand((unsigned int)time(NULL));
	vector<int>v;

	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	v.push_back(30);
	v.push_back(50);
	v.push_back(40);
	v.push_back(10);

	random_shuffle(v.begin(), v.end());
	for_each(v.begin(), v.end(), MyPrint);
	cout << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

merge

功能描述:
两个容器元素合并,并存储到另一容器中
函数原型:

  • merge(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);
    // 容器元素合并,并存储到另一容器中
    // 注意: 两个容器必须是有序的
    // beg1 容器1开始迭代器 // end1 容器1结束迭代器 // beg2 容器2开始迭代器 // end2 容器2结束迭代器
    //dest 目标容器开始迭代器

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

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*i);
	}
	//目标容器
	vector<int>vTarget;
	//开辟空间
	vTarget.resize(v1.size() + v2.size());
	merge(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
	for_each(vTarget.begin(), vTarget.end(), MyPrint);
	cout << endl;
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

reverse

功能描述:
将容器内元素进行反转
函数原型:

  • reverse(iterator beg, iterator end);
    // 反转指定范围的元素
    // beg 开始迭代器// end 结束迭代器

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void MyPrint(int val)
{
	cout << val << " ";
}

void test01()
{
	vector<int>v1;

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

	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
	//反转后
	reverse(v1.begin(), v1.end());
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

常用拷贝和替换算法

学习目标:
掌握常用的拷贝和替换算法
算法简介:

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

copy

功能描述:
容器内指定范围的元素拷贝到另一容器中
函数原型:

  • copy(iterator beg, iterator end, iterator dest);
    // 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
    // beg 开始迭代器
    // end 结束迭代器
    // dest 目标起始迭代器

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void MyPrint(int val)
{
	cout << val << " ";
}

void test01()
{
	vector<int>v1;

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

	vector<int>v2;
	v2.resize(v1.size());
	copy(v1.begin(), v1.end(), v2.begin());
	for_each(v2.begin(), v2.end(), MyPrint);
	cout << endl;
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

replace

功能描述:
将容器内指定范围的旧元素修改为新元素
函数原型:

  • replace(iterator beg, iterator end, oldvalue, newvalue);
    // 将区间内旧元素 替换成 新元素
    // beg 开始迭代器
    // end 结束迭代器
    // oldvalue 旧元素
    // newvalue 新元素

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void MyPrint(int val)
{
	cout << val << " ";
}

void test01()
{
	vector<int>v1;

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

	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;

	//替换后
	replace(v1.begin(), v1.end(), 20, 666);
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

replace_if

功能描述:
将区间内满足条件的元素,替换成指定元素
函数原型:

  • replace_if(iterator beg, iterator end, _pred, newvalue);
    // 按条件替换元素,满足条件的替换成指定元素
    // beg 开始迭代器
    // end 结束迭代器
    // _pred 谓词
    // newvalue 替换的新元素
    示例:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void MyPrint(int val)
{
	cout << val << " ";
}

class Greater30
{
public:
	bool operator()(int val)
	{
		return val > 30;
	}
};

void test01()
{
	vector<int>v1;

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

	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;

	//替换后
	replace_if(v1.begin(), v1.end(), Greater30(), 888);
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

swap

功能描述:
互换两个容器的元素
函数原型:

  • swap(container c1, container c2);
    // 互换两个容器的元素
    // c1容器1
    // c2容器2

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

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*i);
	}
	v1.push_back(10);
	v1.push_back(40);
	v1.push_back(30);
	v1.push_back(20);

	cout << "交换前" << endl;
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
	for_each(v2.begin(), v2.end(), MyPrint);
	cout << endl;

	swap(v1, v2);

	cout << "交换后" << endl;
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
	for_each(v2.begin(), v2.end(), MyPrint);
	cout << endl;
	
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

常用算术生成算法

学习目标:
掌握常用的算术生成算法
注意:
算术生成算法属于小型算法,使用时包含的头文件为 #include
算法简介:

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

accumulate

功能描述:
计算区间内 容器元素累计总和
函数原型:

  • accumulate(iterator beg, iterator end, value);
    // 计算容器元素累计总和
    // beg 开始迭代器
    // end 结束迭代器
    // value 起始值
    示例:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

void MyPrint(int val)
{
	cout << val << " ";
}

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

	int total = accumulate(v1.begin(), v1.end(), 0); //0为起始累加值
	cout << total << endl;
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

fill

功能描述:
向容器中填充指定的元素
函数原型:

  • fill(iterator beg, iterator end, value);
    // 向容器中填充元素
    // beg 开始迭代器
    // end 结束迭代器
    // value 填充的值

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

void MyPrint(int val)
{
	cout << val << " ";
}

void test01()
{
	vector<int>v1;
	v1.resize(10);

	//后期重新填充
	fill(v1.begin(), v1.end(), 100);
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

常用集合算法

学习目标:
掌握常用的集合算法
算法简介:

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

set_intersection

功能描述:
求两个容器的交集
函数原型:

  • set_intersection(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);
    // 求两个集合的交集
    // 注意:两个集合必须是有序序列
    // beg1 容器1开始迭代器 // end1 容器1结束迭代器 // beg2 容器2开始迭代器 // end2 容器2结束迭代器
    //dest 目标容器开始迭代器

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

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 + 3);
	}

	vector<int>vTarget;
	//提前开辟空间
	vTarget.resize(min(v1.size(), v2.size()));
	//获取交集 返回最后位置的迭代器
	vector<int>::iterator itEnd = set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
	for_each(vTarget.begin(), itEnd, MyPrint);
	cout << endl;
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

set_union

功能描述:
求两个集合的并集
函数原型:

  • set_union(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);
    // 求两个集合的并集
    // 注意:两个集合必须是有序序列
    // beg1 容器1开始迭代器 // end1 容器1结束迭代器 // beg2 容器2开始迭代器 // end2 容器2结束迭代器
    //dest 目标容器开始迭代器

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

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 + 3);
	}

	vector<int>vTarget;
	//开辟空间
	vTarget.resize(v1.size() + v2.size());
	vector<int>::iterator itEnd = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
	for_each(vTarget.begin(),itEnd, MyPrint);
	cout << endl;
}
	
int main()
{
	test01();

	system("pause");
	return 0;
}

set_difference

功能描述:
求两个集合的差集
函数原型:

  • set_difference(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);
    // 求两个集合的差集
    // 注意:两个集合必须是有序序列
    // beg1 容器1开始迭代器 // end1 容器1结束迭代器 // beg2 容器2开始迭代器 // end2 容器2结束迭代器
    //dest 目标容器开始迭代器

示例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

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 + 3);
	}

	vector<int>vTarget;
	//开辟空间
	vTarget.resize(max(v1.size(), v2.size()));
	vector<int>::iterator itEnd = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
	cout << "v1和v2的差集" << endl;
	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();

	system("pause");
	return 0;
}
发布了33 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/sinat_38354769/article/details/105515484