跳到正文

Wiki

常用演算法

約 12 分鐘閱讀

本文由簡體中文內容確定性轉換,並受版本化術語表保護。

1.STL- 常用演算法

概述:

  • 演算法主要是由標頭檔案<algorithm> <functional> <numeric>組成。

  • <algorithm>是所有STL標頭檔案中最大的一個,範圍涉及到比較、 交換、查詢、遍歷操作、複製、修改等等

  • <numeric>體積很小,只包括幾個在序列上面進行簡單數學運算的模板函式

  • <functional>定義了一些模板類,用以宣告函式物件。

1.1.常用遍歷演算法

學習目標:

  • 掌握常用的遍歷演算法

演算法簡介:

  • for_each //遍歷容器
  • transform //搬運容器到另一個容器中

1.1.1.for_each

功能描述:

  • 實現遍歷容器

函式原型:

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

    // 遍歷演算法 遍歷容器元素

    // beg 開始迭代器

    // end 結束迭代器

    // _func 函式或者函式物件

示例:

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

using namespace std;

//普通函数
void print01(int val) 
{
	cout << val << " ";
}
//函数对象
class print02 
{
 public:
	void operator()(int val) 
	{
		cout << val << " ";
	}
};

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

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

int main() {

	test01();


	return 0;
}

執行結果:

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9

**總結:**for_each在實際開發中是最常用遍歷演算法,需要熟練掌握

1.1.2.transform

功能描述:

  • 搬運容器到另一個容器中

函式原型:

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

//beg1 源容器開始迭代器

//end1 源容器結束迭代器

//beg2 目標容器開始迭代器

//_func 函式或者函式物件

示例:

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

using namespace std;

//常用遍历算法  搬运 transform

class TransForm
{
public:
	int operator()(int val)
	{
		return val;
	}

};

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

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

	vector<int>vTarget; //目标容器

	vTarget.resize(v.size()); // 目标容器需要提前开辟空间

	transform(v.begin(), v.end(), vTarget.begin(), TransForm());

	for_each(vTarget.begin(), vTarget.end(), MyPrint());
}

int main() {

	test01();


	return 0;
}

執行結果:

0 1 2 3 4 5 6 7 8 9

總結: 搬運的目標容器必須要提前開闢空間,否則無法正常搬運

1.2.常用查詢演算法

學習目標:

  • 掌握常用的查詢演算法

演算法簡介:

  • find //查詢元素
  • find_if //按條件查詢元素
  • adjacent_find //查詢相鄰重複元素
  • binary_search //二分查詢法
  • count //統計元素個數
  • count_if //按條件統計元素個數

1.2.1.find

功能描述:

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

函式原型:

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

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

    // beg 開始迭代器

    // end 結束迭代器

    // value 查詢的元素

示例:

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

using namespace std;

void test01() {

	vector<int> v;
	for (int i = 0; i < 10; i++) {
		v.push_back(i + 1);
	}
	//查找容器中是否有 5 这个元素
	vector<int>::iterator it = find(v.begin(), v.end(), 5);
	if (it == v.end()) 
	{
		cout << "没有找到!" << endl;
	}
	else 
	{
		cout << "找到:" << *it << endl;
	}
}

class Person {
public:
	Person(string name, int age) 
	{
		this->m_Name = name;
		this->m_Age = age;
	}
	//重载==
	bool operator==(const Person& p) 
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age) 
		{
			return true;
		}
		return false;
	}

public:
	string m_Name;
	int m_Age;
};

void test02() {

	vector<Person> v;

	//创建数据
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);

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

	vector<Person>::iterator it = find(v.begin(), v.end(), p2);
	if (it == v.end()) 
	{
		cout << "没有找到!" << endl;
	}
	else 
	{
		cout << "找到姓名:" << it->m_Name << " 年龄: " << it->m_Age << endl;
	}
}

執行結果: 此程式碼塊不含 main 函式,是語法、介面或分檔案示例,不能獨立執行,因此沒有終端輸出。

總結: 利用find可以在容器中找指定的元素,返回值是迭代器

1.2.2.find_if

功能描述:

  • 按條件查詢元素

函式原型:

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

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

    // beg 開始迭代器

    // end 結束迭代器

    // _Pred 函式或者謂詞(返回bool型別的仿函式)

示例:

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

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

	vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
	if (it == v.end()) {
		cout << "没有找到!" << endl;
	}
	else {
		cout << "找到大于5的数字:" << *it << endl;
	}
}

//自定义数据类型
class Person {
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}
public:
	string m_Name;
	int m_Age;
};

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

};

void test02() {

	vector<Person> v;

	//创建数据
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);

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

	vector<Person>::iterator it = find_if(v.begin(), v.end(), Greater20());
	if (it == v.end())
	{
		cout << "没有找到!" << endl;
	}
	else
	{
		cout << "找到姓名:" << it->m_Name << " 年龄: " << it->m_Age << endl;
	}
}

int main() {

	//test01();

	test02();


	return 0;
}

執行結果:

找到姓名:ccc 年龄: 30

總結:find_if按條件查詢使查詢更加靈活,提供的仿函式可以改變不同的策略

1.2.3.adjacent_find

功能描述:

  • 查詢相鄰重複元素

函式原型:

  • adjacent_find(iterator beg, iterator end);

    // 查詢相鄰重複元素,返回相鄰元素的第一個位置的迭代器

    // beg 開始迭代器

    // end 結束迭代器

示例:

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

using namespace std;

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

	//查找相邻重复元素
	vector<int>::iterator it = adjacent_find(v.begin(), v.end());
	if (it == v.end()) {
		cout << "找不到!" << endl;
	}
	else {
		cout << "找到相邻重复元素为:" << *it << endl;
	}
}

執行結果: 此程式碼塊不含 main 函式,是語法、介面或分檔案示例,不能獨立執行,因此沒有終端輸出。

總結:面試題中如果出現查詢相鄰重複元素,記得用STL中的adjacent_find演算法

功能描述:

  • 查詢指定元素是否存在

函式原型:

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

    // 查詢指定的元素,查到 返回true 否則false

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

    // beg 開始迭代器

    // end 結束迭代器

    // value 查詢的元素

示例:

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

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(),2);
	if (ret)
	{
		cout << "找到了" << endl;
	}
	else
	{
		cout << "未找到" << endl;
	}
}

int main() {

	test01();


	return 0;
}

執行結果:

找到了

**總結:**二分查詢法查詢效率很高,值得注意的是查詢的容器中元素必須的有序序列

1.2.5.count

功能描述:

  • 統計元素個數

函式原型:

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

    // 統計元素出現次數

    // beg 開始迭代器

    // end 結束迭代器

    // value 統計的元素

示例:

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

using namespace std;

//内置数据类型
void test01()
{
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(4);
	v.push_back(5);
	v.push_back(3);
	v.push_back(4);
	v.push_back(4);

	int num = count(v.begin(), v.end(), 4);

	cout << "4的个数为: " << num << endl;
}

//自定义数据类型
class Person
{
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}
	bool operator==(const Person & p)
	{
		if (this->m_Age == p.m_Age)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	string m_Name;
	int m_Age;
};

void test02()
{
	vector<Person> v;

	Person p1("刘备", 35);
	Person p2("关羽", 35);
	Person p3("张飞", 35);
	Person p4("赵云", 30);
	Person p5("曹操", 25);

	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);
	v.push_back(p5);
    
    Person p("诸葛亮",35);

	int num = count(v.begin(), v.end(), p);
	cout << "num = " << num << endl;
}
int main() {

	//test01();

	test02();


	return 0;
}

執行結果:

num = 3

總結: 統計自定義資料型別時候,需要配合過載 operator==

1.2.6.count_if

功能描述:

  • 按條件統計元素個數

函式原型:

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

    // 按條件統計元素出現次數

    // beg 開始迭代器

    // end 結束迭代器

    // _Pred 謂詞

示例:

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

using namespace std;

class Greater4
{
public:
	bool operator()(int val)
	{
		return val >= 4;
	}
};

//内置数据类型
void test01()
{
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(4);
	v.push_back(5);
	v.push_back(3);
	v.push_back(4);
	v.push_back(4);

	int num = count_if(v.begin(), v.end(), Greater4());

	cout << "大于4的个数为: " << 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 AgeLess35
{
public:
	bool operator()(const Person &p)
	{
		return p.m_Age < 35;
	}
};
void test02()
{
	vector<Person> v;

	Person p1("刘备", 35);
	Person p2("关羽", 35);
	Person p3("张飞", 35);
	Person p4("赵云", 30);
	Person p5("曹操", 25);

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

	int num = count_if(v.begin(), v.end(), AgeLess35());
	cout << "小于35岁的个数:" << num << endl;
}

int main() {

	//test01();

	test02();


	return 0;
}

執行結果:

小于35岁的个数:2

**總結:**按值統計用count,按條件統計用count_if

1.3.常用排序演算法

學習目標:

  • 掌握常用的排序演算法

演算法簡介:

  • sort //對容器內元素進行排序
  • random_shuffle //洗牌 指定範圍內的元素隨機調整次序
  • merge // 容器元素合併,並存儲到另一容器中
  • reverse // 反轉指定範圍的元素

1.3.1.sort

功能描述:

  • 對容器內元素進行排序

函式原型:

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

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

    // beg 開始迭代器

    // end 結束迭代器

    // _Pred 謂詞

示例:

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

using namespace std;

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

void test01() {
	vector<int> v;
	v.push_back(10);
	v.push_back(30);
	v.push_back(50);
	v.push_back(20);
	v.push_back(40);

	//sort默认从小到大排序
	sort(v.begin(), v.end());
	for_each(v.begin(), v.end(), myPrint);
	cout << endl;

	//从大到小排序
	sort(v.begin(), v.end(), greater<int>());
	for_each(v.begin(), v.end(), myPrint);
	cout << endl;
}

int main() {

	test01();


	return 0;
}

執行結果:

10 20 30 40 50
50 40 30 20 10

**總結:**sort屬於開發中最常用的演算法之一,需熟練掌握

1.3.2.random_shuffle

功能描述:

  • 洗牌 指定範圍內的元素隨機調整次序

函式原型:

  • random_shuffle(iterator beg, iterator end);

    // 指定範圍內的元素隨機調整次序

    // beg 開始迭代器

    // end 結束迭代器

示例:

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

using namespace std;

class myPrint
{
public:
	void operator()(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);
	}
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;

	//打乱顺序
	random_shuffle(v.begin(), v.end());
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;
}

int main() {

	test01();


	return 0;
}

執行結果(隨機數會隨執行環境變化,以下為一次執行示例):

0 1 2 3 4 5 6 7 8 9
2 4 5 8 6 0 9 3 7 1

**總結:**random_shuffle洗牌演算法比較實用,使用時記得加隨機數種子

1.3.3.merge

功能描述:

  • 兩個容器元素合併,並存儲到另一容器中

函式原型:

  • merge(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);

    // 容器元素合併,並存儲到另一容器中

    // 注意: 兩個容器必須是有序的

    // beg1 容器1開始迭代器 // end1 容器1結束迭代器 // beg2 容器2開始迭代器 // end2 容器2結束迭代器 // dest 目標容器開始迭代器

示例:

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

using namespace std;

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

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

	vector<int> vtarget;
	//目标容器需要提前开辟空间
	vtarget.resize(v1.size() + v2.size());
	//合并  需要两个有序序列
	merge(v1.begin(), v1.end(), v2.begin(), v2.end(), vtarget.begin());
	for_each(vtarget.begin(), vtarget.end(), myPrint());
	cout << endl;
}

int main() {

	test01();


	return 0;
}

執行結果:

0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10

**總結:**merge合併的兩個容器必須的有序序列

1.3.4.reverse

功能描述:

  • 將容器內元素進行反轉

函式原型:

  • reverse(iterator beg, iterator end);

    // 反轉指定範圍的元素

    // beg 開始迭代器

    // end 結束迭代器

示例:

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

using namespace std;

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

void test01()
{
	vector<int> v;
	v.push_back(10);
	v.push_back(30);
	v.push_back(50);
	v.push_back(20);
	v.push_back(40);

	cout << "反转前: " << endl;
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;

	cout << "反转后: " << endl;

	reverse(v.begin(), v.end());
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;
}

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

	test01();


	// 返回 0 表示程序正常结束。
	return 0;
}

執行結果:

反转前:
10 30 50 20 40
反转后:
40 20 50 30 10

**總結:**reverse反轉區間內元素,面試題可能涉及到

1.4.常用複製和替換演算法

學習目標:

  • 掌握常用的複製和替換演算法

演算法簡介:

  • copy // 容器內指定範圍的元素複製到另一容器中
  • replace // 將容器內指定範圍的舊元素修改為新元素
  • replace_if // 容器內指定範圍滿足條件的元素替換為新元素
  • swap // 互換兩個容器的元素

1.4.1.copy

功能描述:

  • 容器內指定範圍的元素複製到另一容器中

函式原型:

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

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

    // beg 開始迭代器

    // end 結束迭代器

    // dest 目標起始迭代器

示例:

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

using namespace std;

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

void test01()
{
	vector<int> v1;
	for (int i = 0; i < 10; i++) {
		v1.push_back(i + 1);
	}
	vector<int> v2;
	v2.resize(v1.size());
	copy(v1.begin(), v1.end(), v2.begin());

	for_each(v2.begin(), v2.end(), myPrint());
	cout << endl;
}

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

	test01();


	// 返回 0 表示程序正常结束。
	return 0;
}

執行結果:

1 2 3 4 5 6 7 8 9 10

**總結:**利用copy演算法在複製時,目標容器記得提前開闢空間

1.4.2.replace

功能描述:

  • 將容器內指定範圍的舊元素修改為新元素

函式原型:

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

    // 將區間內舊元素 替換成 新元素

    // beg 開始迭代器

    // end 結束迭代器

    // oldvalue 舊元素

    // newvalue 新元素

示例:

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

using namespace std;

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

void test01()
{
	vector<int> v;
	v.push_back(20);
	v.push_back(30);
	v.push_back(20);
	v.push_back(40);
	v.push_back(50);
	v.push_back(10);
	v.push_back(20);

	cout << "替换前:" << endl;
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;

	//将容器中的20 替换成 2000
	cout << "替换后:" << endl;
	replace(v.begin(), v.end(), 20,2000);
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;
}

int main() {

	test01();


	return 0;
}

執行結果:

替换前:
20 30 20 40 50 10 20
替换后:
2000 30 2000 40 50 10 2000

**總結:**replace會替換區間內滿足條件的元素

1.4.3.replace_if

功能描述:

  • 將區間內滿足條件的元素,替換成指定元素

函式原型:

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

    // 按條件替換元素,滿足條件的替換成指定元素

    // beg 開始迭代器

    // end 結束迭代器

    // _pred 謂詞

    // newvalue 替換的新元素

示例:

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

using namespace std;

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

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

};

void test01()
{
	vector<int> v;
	v.push_back(20);
	v.push_back(30);
	v.push_back(20);
	v.push_back(40);
	v.push_back(50);
	v.push_back(10);
	v.push_back(20);

	cout << "替换前:" << endl;
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;

	//将容器中大于等于的30 替换成 3000
	cout << "替换后:" << endl;
	replace_if(v.begin(), v.end(), ReplaceGreater30(), 3000);
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;
}

int main() {

	test01();


	return 0;
}

執行結果:

替换前:
20 30 20 40 50 10 20
替换后:
20 3000 20 3000 3000 10 20

**總結:**replace_if按條件查詢,可以利用仿函式靈活篩選滿足的條件

1.4.4.swap

功能描述:

  • 互換兩個容器的元素

函式原型:

  • swap(container c1, container c2);

    // 互換兩個容器的元素

    // c1容器1

    // c2容器2

示例:

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

using namespace std;

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

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

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

	cout << "交换后: " << endl;
	swap(v1, v2);
	for_each(v1.begin(), v1.end(), myPrint());
	cout << endl;
	for_each(v2.begin(), v2.end(), myPrint());
	cout << endl;
}

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

	test01();


	// 返回 0 表示程序正常结束。
	return 0;
}

執行結果:

交换前:
0 1 2 3 4 5 6 7 8 9
100 101 102 103 104 105 106 107 108 109
交换后:
100 101 102 103 104 105 106 107 108 109
0 1 2 3 4 5 6 7 8 9

**總結:**swap交換容器時,注意交換的容器要同種型別

1.5.常用算術生成演算法

學習目標:

  • 掌握常用的算術生成演算法

注意:

  • 算術生成演算法屬於小型演算法,使用時包含的標頭檔案為 #include <numeric>

演算法簡介:

  • accumulate // 計算容器元素累計總和

  • fill // 向容器中新增元素

1.5.1.accumulate

功能描述:

  • 計算區間內 容器元素累計總和

函式原型:

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

    // 計算容器元素累計總和

    // beg 開始迭代器

    // end 結束迭代器

    // value 起始值

示例:

#include <iostream>
#include <numeric>
#include <vector>

using namespace std;

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

	int total = accumulate(v.begin(), v.end(), 0);

	cout << "total = " << total << endl;
}

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

	test01();


	// 返回 0 表示程序正常结束。
	return 0;
}

執行結果:

total = 5050

**總結:**accumulate使用時標頭檔案注意是 numeric,這個演算法很實用

1.5.2.fill

功能描述:

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

函式原型:

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

    // 向容器中填充元素

    // beg 開始迭代器

    // end 結束迭代器

    // value 填充的值

示例:

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

using namespace std;

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

void test01()
{

	vector<int> v;
	v.resize(10);
	//填充
	fill(v.begin(), v.end(), 100);

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

int main() {

	test01();


	return 0;
}

執行結果:

100 100 100 100 100 100 100 100 100 100

**總結:**利用fill可以將容器區間內元素填充為 指定的值

1.6.常用集合演算法

學習目標:

  • 掌握常用的集合演算法

演算法簡介:

  • set_intersection // 求兩個容器的交集

  • set_union // 求兩個容器的並集

  • set_difference // 求兩個容器的差集

1.6.1.set_intersection

功能描述:

  • 求兩個容器的交集

函式原型:

  • set_intersection(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);

    // 求兩個集合的交集

    // 注意:兩個集合必須是有序序列

    // beg1 容器1開始迭代器 // end1 容器1結束迭代器 // beg2 容器2開始迭代器 // end2 容器2結束迭代器 // dest 目標容器開始迭代器

示例:

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

using namespace std;

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

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

	vector<int> vTarget;
	//取两个里面较小的值给目标容器开辟空间
	vTarget.resize(min(v1.size(), v2.size()));

	//返回目标容器的最后一个元素的迭代器地址
	vector<int>::iterator itEnd = 
        set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());

	for_each(vTarget.begin(), itEnd, myPrint());
	cout << endl;
}

int main() {

	test01();


	return 0;
}

執行結果:

5 6 7 8 9

總結:

  • 求交集的兩個集合必須的有序序列
  • 目標容器開闢空間需要從兩個容器中取小值
  • set_intersection返回值既是交集中最後一個元素的位置

1.6.2.set_union

功能描述:

  • 求兩個集合的並集

函式原型:

  • set_union(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);

    // 求兩個集合的並集

    // 注意:兩個集合必須是有序序列

    // beg1 容器1開始迭代器 // end1 容器1結束迭代器 // beg2 容器2開始迭代器 // end2 容器2結束迭代器 // dest 目標容器開始迭代器

示例:

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

using namespace std;

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

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

	vector<int> vTarget;
	//取两个容器的和给目标容器开辟空间
	vTarget.resize(v1.size() + v2.size());

	//返回目标容器的最后一个元素的迭代器地址
	vector<int>::iterator itEnd = 
        set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());

	for_each(vTarget.begin(), itEnd, myPrint());
	cout << endl;
}

int main() {

	test01();


	return 0;
}

執行結果:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

總結:

  • 求並集的兩個集合必須的有序序列
  • 目標容器開闢空間需要兩個容器相加
  • set_union返回值既是並集中最後一個元素的位置

1.6.3.set_difference

功能描述:

  • 求兩個集合的差集

函式原型:

  • set_difference(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);

    // 求兩個集合的差集

    // 注意:兩個集合必須是有序序列

    // beg1 容器1開始迭代器 // end1 容器1結束迭代器 // beg2 容器2開始迭代器 // end2 容器2結束迭代器 // dest 目標容器開始迭代器

示例:

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

using namespace std;

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

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

	vector<int> vTarget;
	//取两个里面较大的值给目标容器开辟空间
	vTarget.resize( max(v1.size() , v2.size()));

	//返回目标容器的最后一个元素的迭代器地址
	cout << "v1与v2的差集为: " << endl;
	vector<int>::iterator itEnd = 
        set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
	for_each(vTarget.begin(), itEnd, myPrint());
	cout << endl;

	cout << "v2与v1的差集为: " << endl;
	itEnd = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), vTarget.begin());
	for_each(vTarget.begin(), itEnd, myPrint());
	cout << endl;
}

int main() {

	test01();


	return 0;
}

執行結果:

v1与v2的差集为:
0 1 2 3 4
v2与v1的差集为:
10 11 12 13 14

總結:

  • 求差集的兩個集合必須的有序序列
  • 目標容器開闢空間需要從兩個容器取較大值
  • set_difference返回值既是差集中最後一個元素的位置