本文章是本人黑馬程序員 C++| 匠心之作 從0到1入門學編程的學習筆記
前置文章:
3.9 map / multimap 容器
3.9.1 map 基本概念
簡介:
-
map
中所有元素都是pair
-
pair
中第一個元素為key(鍵值),起到索引作用,第二個元素為value(實值) - 所有元素都會根據(jù)元素的鍵值自動排序
本質:
-
map
/multimap
屬于關聯(lián)式容器肮疗,底層結構是用二叉樹實現(xiàn)
優(yōu)點:
- 可以根據(jù)key值快速找到value值
map
和multimap
區(qū)別:
-
map
不允許有重復key值元素 -
multimap
允許容器中有重復key值
3.9.2 map 構造和賦值
函數(shù)原型:
構造:
-
map<T1, T2> mp;
//map
默認構造函數(shù) -
map(const map &mp);
//拷貝構造函數(shù)
賦值:
-
map &operator=(const map &mp)
//重載等號操作符
示例:
#include <iostream>
#include <map>
using namespace std;
template<typename Key, typename Value>
ostream &operator<<(ostream &cout, map<Key, Value> &m) {
for (typename map<Key, Value>::iterator it = m.begin(); it != m.end(); ++it) {
cout << "鍵值:" << it->first << "刹孔,實值:" << it->second << (it == --m.end() ? " " : " | ");
}
return cout;
}
void test01() {
//map<T1, T2> mp; //map默認構造函數(shù)
map<int, int> m1;
m1.insert(pair<int, int>(3, 30));
m1.insert(pair<int, int>(2, 20));
m1.insert(pair<int, int>(4, 40));
m1.insert(pair<int, int>(1, 10));
cout << "-=-=-=-m1-=-=-=-\n" << m1 << endl;
//map(const map &mp); //拷貝構造函數(shù)
map<int, int> m2(m1);
cout << "-=-=-=-m2-=-=-=-\n" << m2 << endl;
//map &operator=(const map &mp) //重載等號操作符
map<int, int> m3;
m3 = m1;
cout << "-=-=-=-m3-=-=-=-\n" << m3 << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
map
中所有元素都是成對出現(xiàn)辣恋,插入數(shù)據(jù)時要使用對組pair
3.9.3 map 大小和交換
函數(shù)原型:
-
size();
//返回容器中元素的數(shù)目 -
empty();
//判斷容器是否為空 -
swap(mp);
//交換兩個map
容器
示例:
#include <iostream>
#include <map>
using namespace std;
template<typename Key, typename Value>
ostream &operator<<(ostream &cout, map<Key, Value> &m) {
for (auto it = m.begin(); it != m.end(); ++it) {
cout << "鍵值:" << it->first << "男图,實值:" << it->second << (it == --m.end() ? " " : " | ");
}
return cout;
}
void test01() {
map<int, int> m1;
for (int i = 1; i < 6; ++i) { m1.insert(pair<int, int>(i, i * 10)); }
map<int, int> m2;
cout << "-=-=-=-m1-=-=-=-\n" << m1 << endl;
cout << "-=-=-=-m2-=-=-=-\n" << m2 << endl;
//size(); //返回容器中元素的數(shù)目
cout << "m1.size() = " << m1.size() << endl;
cout << "m2.size() = " << m2.size() << endl;
//empty(); //判斷容器是否為空
cout << "m1.empty() = " << m1.empty() << endl;
cout << "m2.empty() = " << m2.empty() << endl;
}
void test02() {
//swap(mp); //交換兩個map容器
map<int, int> m1;
map<int, int> m2;
for (int i = 1; i < 6; ++i) { m1.insert(pair<int, int>(i, i * 10)); }
for (int i = 6; i < 11; ++i) { m2.insert(pair<int, int>(i, i * 10)); }
cout << "交換前:" << endl;
cout << "-=-=-=-m1-=-=-=-\n" << m1 << endl;
cout << "-=-=-=-m2-=-=-=-\n" << m2 << endl;
m1.swap(m2);
cout << "交換后:" << endl;
cout << "-=-=-=-m1-=-=-=-\n" << m1 << endl;
cout << "-=-=-=-m2-=-=-=-\n" << m2 << endl;
}
int main() {
test01();
test02();
system("pause");
return 0;
}
3.9.4 map 插入和刪除
函數(shù)原型:
-
insert(elem);
//在容器中插入元素 -
clear();
//清除所有元素 -
erase(pos);
//刪除pos
迭代器所指的元素,返回下一個元素的迭代器 -
erase(beg, end);
//刪除區(qū)間beg
end
的所有元素,返回下一個元素的迭代器 -
erase(key);
//刪除容器中值為elem
的元素
示例:
#include <iostream>
#include <map>
using namespace std;
template<typename Key, typename Value>
ostream &operator<<(ostream &cout, map<Key, Value> &m) {
for (auto it = m.begin(); it != m.end(); ++it) {
cout << "鍵值:" << it->first << "思犁,實值:" << it->second << (it == --m.end() ? " " : " | ");
}
return cout;
}
void test01() {
map<int, int> m;
//insert(elem); //在容器中插入元素
m.insert(pair<int, int>(1, 10));
m.insert(make_pair(2, 20));
m.insert(map<int, int>::value_type(3, 30));
m[4] = 40;
//[]不建議插入,可以利用key訪問value
//cout << m[4] << endl;
cout << "-=-=-=-m-=-=-=-\n" << m << endl;
//erase(pos); //刪除pos迭代器所指的元素进肯,返回下一個元素的迭代器
m.erase(m.begin());
cout << "-=-=-=-m-=-=-=-\n" << m << endl;
//erase(beg, end); //刪除區(qū)間[beg, end)的所有元素激蹲,返回下一個元素的迭代器
m.erase(++m.begin(), --m.end());
cout << "-=-=-=-m-=-=-=-\n" << m << endl;
//erase(key); //刪除容器中值為elem的元素
m.erase(2);
cout << "-=-=-=-m-=-=-=-\n" << m << endl;
//clear(); //清除所有元素
m.clear();
cout << "-=-=-=-m-=-=-=-\n" << m << endl;
}
int main() {
test01();
system("pause");
return 0;
}
3.9.5 map 查找和統(tǒng)計
函數(shù)原型:
-
find(key);
//查找key
是否存在:若存在,返回該鍵的元素迭代器江掩;若不存在学辱,返回set.end();
-
count(key);
//統(tǒng)計key
的元素個數(shù)
示例:
#include <iostream>
#include <map>
using namespace std;
template<typename Key, typename Value>
ostream &operator<<(ostream &cout, map<Key, Value> &m) {
for (auto it = m.begin(); it != m.end(); ++it) {
cout << "鍵值:" << it->first << ",實值:" << it->second << (it == --m.end() ? " " : " | ");
}
return cout;
}
void test01() {
map<int, int> m;
for (int i = 1; i < 11; ++i) { m.insert(pair<int, int>(i, i * 10)); }
cout << "-=-=-=-m-=-=-=-\n" << m << endl;
map<int, int>::iterator pos = m.find(3);
//map<int, int>::iterator pos = m.find(100);
if (pos != m.end()) { cout << "查找到了元素环形,key = " << pos->first << ", value = " << pos->second << endl; }
else { cout << "未查找到元素策泣!" << endl; }
//map<int, int>::size_type num = m.count(10);
int num = m.count(10);
//map不允許插入重復的值,count統(tǒng)計結果要么是0抬吟,要么是1
cout << "m.count(10) = " << num << endl;
//multimap的統(tǒng)計可能大于1
}
int main() {
test01();
system("pause");
return 0;
}
總結:
- 查找 ---
find()
//返回的是迭代器- 統(tǒng)計 ---
count()
3.9.6 容器排序
主要技術點:
- 利用仿函數(shù)萨咕,可以改變排序規(guī)則
示例:
#include <iostream>
#include <map>
using namespace std;
//改變排序規(guī)則
class MyCompare {
public:
bool operator()(const int v1,const int v2) { return v1 > v2; }
};
template<typename Key, typename Value>
ostream &operator<<(ostream &cout, map<Key, Value> &m) {
for (auto it = m.begin(); it != m.end(); ++it)
cout << "鍵值:" << it->first << ",實值:" << it->second << (it == --m.end() ? " " : " | ");
return cout;
}
template<typename Key, typename Value>
ostream &operator<<(ostream &cout, map<Key, Value, MyCompare> &m) {
for (auto it = m.begin(); it != m.end(); ++it)
cout << "鍵值:" << it->first << "火本,實值:" << it->second << (it == --m.end() ? " " : " | ");
return cout;
}
void test01() {
map<int, int> m1;
for (int i = 1; i < 11; ++i) { m1.insert(pair<int, int>(i, i * 10)); }
cout << "-=-=-=-m1-=-=-=-\n" << m1 << endl;
map<int,int, MyCompare> m2;
m2.insert(make_pair(1, 10));
for (int i = 1; i < 11; ++i) { m2.insert(make_pair(i, i * 10)); }
cout << "-=-=-=-m2-=-=-=-\n" << m2 << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
- 利用仿函數(shù)可以指定
map
容器的排序規(guī)則- 對于自定義數(shù)據(jù)類型危队,
map
必須要指定排序規(guī)則,同set
容器
3.10 案例 - 員工分組
3.10.1 案例描述
- 公司今天招聘了10個員工(ABCDEFGHI)钙畔,10名員工進入公司之后交掏,需要指派員工在那個部門工作
- 員工信息::姓名、工資組成刃鳄;部門分為:策劃盅弛、美術、研發(fā)
- 隨機給10名員工分配部門和工資
- 通過multimap進行信息的插入key(部門編號) 和value(員工)
- 分部門顯示員工信息
3.10.2 實現(xiàn)步驟
- 創(chuàng)建10名員工叔锐,放到
vector
中 - 遍歷
vector
容器挪鹏,取出每個員工,進行隨機分組 - 分組后愉烙,將員工部門編號作為key讨盒,具體員工作為value,放入到
multimap
容器中 - 分部門顯示員工信息
案例代碼:
#include <ctime>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#define PLANNING 0
#define ART 1
#define RESEARCH 2
using namespace std;
class Worker {
public:
string m_Name;
double m_Salary;
};
void createWorker(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() % 10001 + 10000;
//將員工放入容器
v.push_back(worker);
}
}
void setDept(vector<Worker> &v, multimap<int, Worker> &m) {
for (vector<Worker>::iterator it = v.begin(); it != v.end(); ++it) {
//隨機部門編號
int deptId = rand() % 3;
//將員工插入數(shù)組
m.insert(make_pair(deptId, *it));
}
}
void showWorkerByGroup(multimap<int, Worker> &m) {
cout << "策劃部門:" << endl;
multimap<int, Worker>::iterator pos = m.find(PLANNING); //策劃部門起始位置
int count = m.count(PLANNING); //策劃部門人數(shù)
for (int index = 0; pos != m.end() && index < count; ++pos, ++index) {
cout << " - 姓名:" << pos->second.m_Name << "\t工資:" << pos->second.m_Salary << endl;
}
cout << "美術部門:" << endl;
pos = m.find(ART); //美術部門起始位置
count = m.count(ART); //美術部門人數(shù)
for (int index = 0; pos != m.end() && index < count; ++pos, ++index) {
cout << " - 姓名:" << pos->second.m_Name << "\t工資:" << pos->second.m_Salary << endl;
}
cout << "研發(fā)部門:" << endl;
pos = m.find(RESEARCH); //研發(fā)部門起始位置
count = m.count(RESEARCH); //研發(fā)部門人數(shù)
for (int index = 0; pos != m.end() && index < count; ++pos, ++index) {
cout << " - 姓名:" << pos->second.m_Name << "\t工資:" << pos->second.m_Salary << endl;
}
}
int main() {
srand((unsigned int)time(NULL));
//創(chuàng)建員工
vector<Worker> vWorkers;
createWorker(vWorkers);
//員工分組
multimap<int, Worker> mWorker;
setDept(vWorkers, mWorker);
//分組顯示員工
showWorkerByGroup(mWorker);
system("pause");
return 0;
}
4 STL - 函數(shù)對象
4.1 函數(shù)對象
4.1.1 函數(shù)對象概念
概念:
- 重載函數(shù)調用操作符的類步责,其對象常常稱作函數(shù)對象
-
函數(shù)對象使用重載的
()
時返顺,行為類似函數(shù)調用禀苦,因此也叫仿函數(shù)
本質:
- 函數(shù)對象是一個類遂鹊,不是一個函數(shù)
4.1.2 函數(shù)對象的調用
特點:
- 函數(shù)對象在使用時秉扑,可以像普通函數(shù)那樣調用慧邮,可以有參數(shù)舟陆,可以有返回值
- 函數(shù)對象超出普通函數(shù)的概念,函數(shù)對象可以有自己的狀態(tài)
- 函數(shù)對象可以作為參數(shù)傳遞
示例:
#include <iostream>
#include <string>
using namespace std;
class MyAdd {
public:
int operator()(int v1, int v2) { return v1 + v2; }
};
class MyPrint {
public:
MyPrint() { this->count = 0; }
void operator()(const string &mString) {
cout << mString << endl;
this->count++;
}
int count = 0;
};
//函數(shù)對象可以作為參數(shù)傳遞
void doPrint(MyPrint &mp, string mString) {
mp(mString);
}
void test01() {
MyAdd myAdd;
//函數(shù)對象在使用時秦躯,可以像普通函數(shù)那樣調用,可以有參數(shù)倡缠,可以有返回值
cout << myAdd(10, 10) << endl;
MyPrint myPrint;
myPrint("Hello world");
myPrint("Hello world");
myPrint("Hello world");
myPrint("Hello world");
myPrint("Hello world");
//函數(shù)對象超出普通函數(shù)的概念毡琉,函數(shù)對象可以有自己的狀態(tài)
cout << "myPrint調用了" << myPrint.count << "次" << endl;
//函數(shù)對象可以作為參數(shù)傳遞
doPrint(myPrint, "Hello C++");
}
int main() {
test01();
system("pause");
return 0;
}
4.2 謂詞
4.2.1 謂詞概念
概念:
- 返回
bool
類型的仿函數(shù)稱為謂詞 - 如果
operator()
接受一個參數(shù),那么叫做一元謂詞 - 如果
operator()
接受兩個參數(shù)身辨,那么叫做二元謂詞
4.2.2 一元謂詞
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MoreThanFive {
public:
bool operator()(int val) { return val > 5; }
};
void test01() {
vector<int> v;
v.reserve(10);
for (int i = 0; i < 10; ++i) { v.push_back(i + 1); }
//查找容器中大于5的數(shù)字
vector<int>::iterator it = find_if(v.begin(), v.end(), MoreThanFive()); //MoreThanFive()是一個匿名對象
if (it == v.end()) { cout << "未找到大于5的數(shù)字"; }
else { cout << "找到了大于5的數(shù)字為" << *it << endl; }
}
int main() {
test01();
system("pause");
return 0;
}
4.2.3 二元謂詞
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MySort {
public:
bool operator()(int val1, int val2) { return val1 > val2; }
};
ostream &operator<<(ostream &cout, const vector<int> &v) {
for (vector<int>::const_iterator it = v.begin(); it != v.end(); ++it) {
cout << *it << (it == --v.end() ? "" : ", ");
}
return cout;
}
void test01() {
vector<int> v;
v.reserve(10);
for (int i = 0; i < 10; ++i) { v.push_back(i + 1); }
cout << "v: " << v << endl;
sort(v.begin(), v.end(), MySort());
cout << "v: " << v << endl;
}
int main() {
test01();
system("pause");
return 0;
}
4.3 內建函數(shù)對象
4.3.1 內建函數(shù)對象意義
概念:
- STL內建了一些函數(shù)對象
分類:
- 算術仿函數(shù)
- 關系仿函數(shù)
- 邏輯仿函數(shù)
用法:
- 這些仿函數(shù)所產(chǎn)生的對象煌珊,用法和一般函數(shù)完全相同
- 使用內建函數(shù)對象定庵,需要引入頭文件
#include <functional>
4.3.2 算術仿函數(shù)
功能描述:
- 實現(xiàn)四則運算
- 其中
negate
是一元運算蔬浙,其它都是二元
仿函數(shù)原型:
-
template<class T> T plus<T>
//加法仿函數(shù) -
template<class T> T minus<T>
//減法仿函數(shù) -
template<class T> T multiplies<T>
//乘法仿函數(shù) -
template<class T> T divides<T>
//除法仿函數(shù) -
template<class T> T modulus<T>
//取模仿函數(shù) -
template<class T> T negate<T>
//取反仿函數(shù)
示例:
#include <iostream>
#include <functional>
using namespace std;
void test01() {
int a = 5, b = 17;
//template<class T> T plus<T> //加法仿函數(shù)
plus<int> plus;
cout << plus(a, b) << endl;
//template<class T> T minus<T> //減法仿函數(shù)
minus<int> minus;
cout << minus(a, b) << endl;
//template<class T> T multiplies<T> //乘法仿函數(shù)
multiplies<int> multiplies;
cout << multiplies(a, b) << endl;
//template<class T> T divides<T> //除法仿函數(shù)
divides<int> divides;
cout << divides(b, a) << endl;
//template<class T> T modulus<T> //取模仿函數(shù)
modulus<int> modulus;
cout << modulus(b, a) << endl;
//template<class T> T negate<T> //取反仿函數(shù)
negate<int> negate;
cout << negate(a) << endl;
}
int main() {
test01();
system("pause");
return 0;
}
4.3.3 關系仿函數(shù)
功能描述:
- 實現(xiàn)關系對比
仿函數(shù)原型:
-
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 <algorithm>
#include <functional>
using namespace std;
class MyCompare {
bool operator()(int v1, int v2) { return v1 > v2; }
};
ostream &operator<<(ostream &cout, const vector<int> &v) {
for (auto it :v) { cout << it << (it == *(--v.end()) ? "" : ", "); }
return cout;
}
void test01() {
vector<int> v;
v.reserve(10);
for (int i = 0; i < 10; ++i) { v.push_back(i + 1); }
cout << v << endl;
//template<class T> bool greater<T> //大于
sort(v.begin(), v.end(), greater<int>());
//sort(v.begin(), v.end(), MyCompare());
cout << v << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:關系仿函數(shù)中最常用的就是
greater<>
大于
4.3.4 邏輯仿函數(shù)
函數(shù)原型:
-
template<class T> bool logical_and<T>
//邏輯與 -
template<class T> bool logical_or<T>
//邏輯或 -
template<class T> bool logical_nor<T>
//邏輯非
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
ostream &operator<<(ostream &cout, const vector<bool> &v) {
for (auto it :v) { cout << it << " "; }
return cout;
}
void test01() {
vector<bool> v1;
v1.reserve(10);
for (int i = 0; i < 10; ++i) {
v1.push_back(rand() % 2 != 0);
}
cout << "v1: " << v1 << endl;
vector<bool> v2;
v2.resize(v1.size());
//template<class T> bool logical_nor<T> //邏輯非
transform(v1.begin(), v1.end(), v2.begin(), logical_not<bool>());
cout << "v2: " << v2 << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:邏輯仿函數(shù)實際運用較少,了解即可
5 STL - 常用算法
概述:
- 算法主要是由頭文件
<algorithm>
俱病、<functional>
和<numeric>
組成 -
<algorithm>
是所有STL頭文件中最大的一個亮隙,范圍涉及到比較、交換咱揍、查找颖榜、遍歷操作煤裙、復制硼砰、修改等 -
<numeric>
體積很小题翰,只包括幾個在序列上上面進行簡單數(shù)學比較的函數(shù)模板 -
<functional>
定義了一些模板類豹障,用以聲明函數(shù)對象
5.1 常用遍歷算法
算法簡介:
-
for_each
//遍歷容器 -
transform
//搬運容器到另一個容器中
5.1.1 for_each
功能描述:
- 實現(xiàn)遍歷容器
函數(shù)原型:
-
for_each(iterator beg, iterator end, _Func);
// 遍歷算法血公,遍歷容器元素
//
beg
開始迭代器//
end
結束迭代器//
_func
函數(shù)或函數(shù)對象
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//普通函數(shù)
void myPrint01(int val) { cout << val << " "; }
//仿函數(shù)
class MyPrint02 {
public:
void operator()(int val) { cout << val << " "; }
};
void test01() {
vector<int> v;
v.reserve(10);
for (int i = 0; i < 10; ++i) {
v.push_back(i + 1);
}
for_each(v.begin(), v.end(), myPrint01);
cout << endl;
for_each(v.begin(), v.end(), MyPrint02());
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
for_each
在實際開發(fā)中是最常用的遍歷算法累魔,需要熟練掌握
5.1.2 transform
功能描述:
- 搬運容器到另一個容器中
函數(shù)原型:
-
transform(iterator beg1, iterator end1, iterator beg2, _func)
//
beg1
源容器開始迭代器//
end1
源容器//
beg2
目標容器開始迭代器/
_func
函數(shù)或者函數(shù)對象
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MyTransform {
public:
int operator()(int val) { return val * 10; }
};
class MyPrint {
public:
void operator()(int val) { cout << val << " "; }
};
void test01() {
vector<int> v; //源容器
v.reserve(10);
for (int i = 0; i < 10; ++i) {
v.push_back(i + 1);
}
vector<int> vTarget;
vTarget.resize(10);
transform(v.begin(), v.end(), vTarget.begin(), MyTransform());
for_each(vTarget.begin(), vTarget.end(), MyPrint());
}
int main() {
test01();
system("pause");
return 0;
}
總結:搬運的目標容器必須要提前開辟空間吕世,否則無法正常搬運
5.2 常用查找算法
算法簡介:
-
find
//查找元素 -
find_if
//條件查找元素 -
adjacent_find
//查找相鄰重復元素 -
binary_search
//二分查找法 -
count
//統(tǒng)計元素個數(shù) -
count_if
//按條件統(tǒng)計元素個數(shù)
5.2.1 find
功能描述:
- 查找指定元素命辖,找到返回指定元素的迭代器尔艇,找不到返回結束迭代器
end()
函數(shù)原型:
-
find(inerator beg, iterator end, value);
// 查找指定元素漓帚,找到返回指定元素的迭代器尝抖,找不到返回結束迭代器
end()
//
beg
開始迭代器//
end
結束迭代器//
value
查找的元素
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Person {
public:
Person(const string &name, int age) : m_Name(name), m_Age(age) {}
//重載operator== 底層find知道如何對比Person數(shù)據(jù)
bool operator==(const Person &person) { return this->m_Name == person.m_Name && this->m_Age == person.m_Age; }
string m_Name;
int m_Age;
};
void test01() {
//內置數(shù)據(jù)類型
vector<int> v;
v.reserve(10);
for (int i = 0; i < 10; ++i) { v.push_back(i + 1); }
vector<int>::iterator it = find(v.begin(), v.end(), 5);
if (it == v.end()) { cout << "未找到元素衙熔!" << endl; }
else { cout << "找到" << *it << endl; }
//自定義數(shù)據(jù)類型
vector<Person> vPerson;
Person p1("A", 10);
Person p2("B", 20);
Person p3("C", 30);
Person p4("D", 40);
vPerson.push_back(p1);
vPerson.push_back(p2);
vPerson.push_back(p3);
vPerson.push_back(p4);
vector<Person>::iterator itPerson = find(vPerson.begin(), vPerson.end(), p2);
if (it == v.end()) { cout << "未找到元素红氯!" << endl; }
else { cout << "找到Person" << itPerson->m_Name << endl; }
}
int main() {
test01();
system("pause");
return 0;
}
總結:
- 利用
find
可以在容器中找到指定的元素痢甘,返回值是迭代器- 自定義數(shù)據(jù)類型需要重載
operator==
塞栅,讓底層find
知道如何對比數(shù)據(jù)
5.2.2 find_if
功能描述:
- 按條件查找元素
函數(shù)原型:
-
find_if(inerator beg, iterator end, _Pred);
// 按值查找元素放椰,找到返回指定位置迭代器砾医,未找到返回結束迭代器位置
//
beg
開始迭代器//
end
結束迭代器//
_Pred
函數(shù)或者謂詞(返回bool
類型的仿函數(shù))
示例:
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
using namespace std;
//內置數(shù)據(jù)類型
class moreThanFive {
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(), moreThanFive());
if (it == v.end()) { cout << "沒有找到如蚜!" << endl; }
else { cout << "找到" << *it << endl; }
}
//自定義數(shù)據(jù)類型
class Person {
public:
Person(string name, int age) : name(std::move(name)), age(age) {}
string name;
int age;
};
class moreThanTwenty {
public:
bool operator()(Person &person) {
return person.age > 20;
}
};
void test02() {
vector<Person> v;
string names[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};
for (int i = 0; i < 10; ++i) { v.emplace_back(names[i], (i + 1) * 5); }
vector<Person>::iterator it = find_if(v.begin(), v.end(), moreThanTwenty());
if (it == v.end()) { cout << "沒有找到涎显!" << endl; }
else { cout << "找到了" << it->age << "歲的" << it->name << endl; }
}
int main() {
test01();
test02();
system("pause");
return 0;
}
5.2.3 adjacent_find
功能描述:
- 查找相鄰重復元素
函數(shù)原型:
-
adjacent_find(inerator beg, iterator end);
// 查找相鄰重復元素期吓,返回相鄰元素的第一個位置的迭代器
//
beg
開始迭代器//
end
結束迭代器
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void test01() {
vector<int> v;
int nums[] = {0, 2, 0, 3, 1, 4, 3, 3, 2, 2, 0, 4};
for (auto i : nums) { v.push_back(i); }
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;
}
5.2.4 binary_search
功能描述:
- 查找指定元素是否存在
函數(shù)原型:
-
binary_search(inerator beg, iterator end, value);
// 查找指定的元素潭千,查找到返回
true
刨晴,否則返回false
// 注意:在無需序列中不可用
//
beg
開始迭代器//
end
結束迭代器//
value
查找的元素
示例:
#include <iostream>
#include <vector>
#include <random>
#include <ctime>
#include <algorithm>
using namespace std;
const int SIZE = 100000;
default_random_engine e(time(nullptr));
uniform_int_distribution<int> d(-SIZE * 100, SIZE * 100);
void test01() {
vector<int> v;
v.reserve(SIZE);
for (int i = 0; i < SIZE; ++i) { v.push_back(d(e)); }
//在無需序列中不可用
sort(v.begin(), v.end());
int findNum = v.at(5000);
bool ret = binary_search(v.begin(), v.end(), findNum);
if (ret) { cout << "找到了" << findNum << endl; }
else { cout << "未找到" << findNum << endl; }
}
int main() {
test01();
system("pause");
return 0;
}
總結:二分查找法查找效率很高茄靠,值得注意的是查找的容器中元素必須是有序序列
5.2.5 count
功能:
- 統(tǒng)計元素個數(shù)
函數(shù)原型:
-
count(iterator beg, iterator end, value);
// 統(tǒng)計元素出現(xiàn)次數(shù)
/ /
beg
開始迭代器/ /
end
結束迭代器/ /
value
統(tǒng)計的元素
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//統(tǒng)計內置數(shù)據(jù)類型
void test01() {
vector<int> v;
int nums[] = {10, 40, 30, 40, 20, 40};
for (auto num :nums) { v.push_back(num); }
int numCount = count(v.begin(), v.end(), 40);
cout << "40出現(xiàn)了" << numCount << "次慨绳!" << endl;
}
//統(tǒng)計自定義數(shù)據(jù)類型
class Person {
public:
Person(string name, int age) {
this->name = name;
this->age = age;
}
//重載operator==
bool operator==(const Person &p) { return this->age == p.age; }
string name;
int age;
};
void test02() {
vector<Person> v;
string names[] = {"劉備", "關羽", "張飛", "趙云", "曹操"};
int ages[] = {35, 35, 35, 30, 40};
for (int i = 0; i < sizeof(names) / sizeof(names[0]); ++i) { v.emplace_back(Person(names[i], ages[i])); }
Person p("諸葛亮", 35);
int numCount = count(v.begin(), v.end(), p);
cout << "和諸葛亮同歲的有" << numCount << "人脐雪!" << endl;
}
int main() {
test01();
test02();
system("pause");
return 0;
}
5.2.7 count_if
功能:
- 按條件統(tǒng)計元素個數(shù)
函數(shù)原型:
-
count(iterator beg, iterator end, _Pred);
// 按條件統(tǒng)計元素出現(xiàn)次數(shù)
/ /
beg
開始迭代器/ /
end
結束迭代器/ /
_Pred
謂詞
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//統(tǒng)計內置數(shù)據(jù)類型
class moreThanTwenty {
public:
bool operator()(int val) { return val > 20; }
};
void test01() {
vector<int> v;
int nums[] = {10, 40, 30, 20, 40, 20};
for (auto num :nums) { v.push_back(num); }
int numCount = count_if(v.begin(), v.end(), moreThanTwenty());
cout << "大于20的元素有" << numCount << "個召锈!" << endl;
}
//統(tǒng)計自定義數(shù)據(jù)類型
class Person {
public:
Person(string name, int age) {
this->name = name;
this->age = age;
}
string name;
int age;
};
class ageGreater {
public:
bool operator()(const Person &p) { return p.age > 30; }
};
void test02() {
vector<Person> v;
string names[] = {"劉備", "關羽", "張飛", "趙云", "曹操"};
int ages[] = {35, 35, 35, 20, 40};
for (int i = 0; i < sizeof(names) / sizeof(names[0]); ++i) { v.emplace_back(Person(names[i], ages[i])); }
int numCount = count_if(v.begin(), v.end(), ageGreater());
cout << "年齡大于30歲的有" << numCount << "人涨岁!" << endl;
}
int main() {
test01();
test02();
system("pause");
return 0;
}
5.3 常用排序算法
算法簡介:
-
sort
//對容器內元素進行排序 -
random_shuffle
//洗牌:指定范圍內的元素隨機調整次序 -
merge
//容器元素合并梢薪,并儲存到另一容器中 -
reverse
//反轉指定范圍的元素
5.3.1 sort
功能描述:
- 對容器內元素進行排序
函數(shù)原型:
-
sort(iterator beg, iterator end, _Pred);
// 對容器內元素進行排序
//
beg
起始迭代器//
end
結束迭代器//
_Pred
謂詞
示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void myPrint(int val) { cout << val << " "; }
void test01() {
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(5);
v.push_back(2);
v.push_back(4);
//升序
sort(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint);
cout << endl;
//降序
sort(v.begin(), v.end(), greater<>());
for (auto it:v) { cout << it << (it == *(--v.end()) ? "\n" : " "); }
}
int main() {
test01();
system("pause");
return 0;
}
5.3.2 random_shuffle
功能描述:
- 洗牌:指定范圍內的元素隨機調整次序
函數(shù)原型:
-
random_shuffle(iterator beg, iterator end);
// 指定范圍內的元素隨機調整次序
//
beg
起始迭代器//
end
結束迭代器
示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
using namespace std;
void test01() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i + 1);
}
random_shuffle(v.begin(), v.end());
for (auto it:v) { cout << it << (it == *(--v.end()) ? "\n" : " "); }
}
int main() {
srand((unsigned int) time(nullptr));
test01();
system("pause");
return 0;
}
5.3.3 merge
功能描述:
- 容器元素合并,并儲存到另一容器中
函數(shù)原型:
-
merge(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;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << (it == *(--v.end()) ? "" : ", "); }
return cout;
}
void test01() {
vector<int> v1;
for (int i = 0; i < 10; ++i) { v1.push_back(i * 2 + 1); }
vector<int> v2;
for (int i = 0; i < 10; ++i) { v2.push_back((i + 1) * 2); }
cout << "v1: " << v1 << endl;
cout << "v2: " << v2 << endl;
vector<int> vTarget;
vTarget.resize(v1.size() + v2.size());
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
cout << vTarget << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
merge
合并的兩個容器必須是有序序列
5.3.4 reverse
功能描述:
- 反轉指定范圍的元素
函數(shù)原型:
-
reverse(iterator beg, iterator end);
// 反轉指定范圍的元素
//
beg
開始迭代器//
end
結束迭代器
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << (it == *(--v.end()) ? "" : ", "); }
return cout;
}
void test01() {
vector<int> v;
for (int i = 0; i < 10; ++i) { v.push_back(i + 1); }
cout << "反轉前:" << v << endl;
reverse(v.begin(), v.end());
cout << "反轉后:" << v << endl;
}
int main() {
test01();
system("pause");
return 0;
}
5.4 常用拷貝和替換算法
算法簡介:
-
copy
//容器內指定范圍的元素拷貝到另一容器中 -
replace
//將容器內指定范圍的舊元素修改為新元素 -
replace_if
//容器內指定范圍滿足條件的元素替換為新元素 -
swap
//互換兩個容器的元素
5.4.1 copy
功能描述
- 容器內指定范圍的元素拷貝到另一容器中
函數(shù)原型:
-
copy(iterator beg, iterator end, iterator dest)
// 容器內指定范圍的元素拷貝到另一容器中
//beg
源容器開始迭代器
//end
源容器結束迭代器
//dest
目標容器開始迭代器
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << (it == *(--v.end()) ? "" : ", "); }
return cout;
}
void test01() {
vector<int> v1;
for (int i = 0; i < 10; ++i) { v1.push_back(i + 1); }
cout << "v1: " << v1 << endl;
vector<int> v2;
v2.resize(v1.size());
copy(v1.begin(), v1.end(), v2.begin());
cout << "v2: " << v2 << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:利用
copy
算法在拷貝時歧胁,目標容器記得提前開辟空間
5.4.2 replac
功能描述
- 將容器內指定范圍的舊元素修改為新元素
函數(shù)原型:
-
replace(iterator beg, iterator end, oldvalue, newvalue);
// 將容器內指定范圍的舊元素修改為新元素
//
beg
開始迭代器//
end
結束迭代器//
oldvalue
舊元素//
newvalue
新元素
示例
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << (it == *(--v.end()) ? "" : ", "); }
return cout;
}
void test01() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back((i + 1) * 10);
if (i == 4 || i == 5) { for (int j = 0; j < i; ++j) { v.push_back((i + 1) * 10); }}
}
cout << "替換前: " << v << endl;
replace(v.begin(), v.end(), 50, 5);
cout << "替換后: " << v << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
replace
會替換區(qū)間內所有滿足條件的元素
5.4.3 replace_if
功能描述
- 容器內指定范圍滿足條件的元素替換為新元素
函數(shù)原型:
-
replace_if(iterator beg, iterator end, _Pred, newvalue);
// 容器內指定范圍滿足條件的元素替換為新元素
//
beg
開始迭代器//
end
結束迭代器//
_Pred
謂詞//
newvalue
替換的新元素
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << " "; }
return cout;
}
class moreThanFifty {
public:
bool operator()(int val) { return val > 50; }
};
void test01() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back((i + 1) * 10);
if (i == 4 || i == 5) { for (int j = 0; j < i; ++j) { v.push_back((i + 1) * 10); }}
}
cout << "替換前: " << v << endl;
replace_if(v.begin(), v.end(), moreThanFifty(), 12321);
cout << "替換后: " << v << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
replace_if
按條件查找屠缭,可以利用仿函數(shù)靈活篩選滿足條件
5.4.4 swap
功能描述
- 互換兩個容器的元素
函數(shù)原型:
-
swqp(container c1, container c2);
// 互換兩個容器的元素
//
c1
容器1//
c2
容器2
示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << " "; }
return cout;
}
void test01() {
cout << "-=-=-=-=-=-=-=-=- 交換前 -=-=-=-=-=-=-=-=-" << endl;
vector<int> v1;
for (int i = 0; i < 10; ++i) { v1.push_back(i * 2 + 1); }
cout << "v1: " << v1 << endl;
vector<int> v2;
for (int i = 0; i < 10; ++i) { v2.push_back((i + 1) * 2); }
cout << "v2: " << v2 << endl;
cout << "-=-=-=-=-=-=-=-=- 交換后 -=-=-=-=-=-=-=-=-" << endl;
swap(v1, v2);
cout << "v1: " << v1 << endl;
cout << "v2: " << v2 << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
swqp
交換容器時,注意交換的容器要同種類型
5.5 常用算數(shù)生成算法
注意:
- 算數(shù)生成算法屬于小型算法奄喂,使用時包含的頭文件為
#include <numeric>
算法簡介:
-
accumulate
//計算容器元素累計總和 -
fill
//向容器中填充指定元素
5.5.1 accumulate
功能描述:
- 計算容器元素累計總和
函數(shù)原型:
-
accumulate(iterator beg, itorator end, value);
// 計算容器元素累計總和
//
beg
開始迭代器//
end
結束迭代器//
value
起始累加值
示例:
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << " "; }
return cout;
}
void test01() {
vector<int> v;
for (int i = 0; i < 100; ++i) { v.push_back(i + 1); }
int sum = accumulate(v.begin(), v.end(), 0);
cout << "sum(1, 100) = " << sum << endl;
}
int main() {
test01();
system("pause");
return 0;
}
5.5.2 fill
功能描述:
- 向容器中填充指定元素
函數(shù)原型:
-
fill(iterator beg, itorator end, value);
// 向容器中填充指定元素
//
beg
開始迭代器//
end
結束迭代器//
value
填充的值
示例:
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << " "; }
return cout;
}
void test01() {
vector<int> v;
v.resize(10);
fill(v.begin(), v.end(), 123);
cout << "v: " << v << endl;
fill(v.begin(), v.end(), 321);
cout << "v: " << v << endl;
}
int main() {
test01();
system("pause");
return 0;
}
5.6 常用集合算法
算法簡介:
-
set_intersection
//求兩個容器的交集 -
set_union
//求兩個容器的并集 -
set_difference
//求兩個容器的差集
5.6.1 set_intersection
功能描述:
- 求兩個容器的交集
函數(shù)原型:
-
set_intersection(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);
// 求兩個容器的交集
// 注意:兩個集合必須是有序數(shù)列
//
beg1
容器1開始迭代器//
end1
容器1結束迭代器//
beg2
容器2開始迭代器//
end2
容器2結束迭代器//
dest
目標容器開始迭代器
示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << " "; }
return cout;
}
void test01() {
vector<int> v1;
for (int i = 0; i < 10; ++i) { v1.push_back(i + 1); }
cout << "v1: " << v1 << endl;
vector<int> v2;
for (int i = -6; i < 5; ++i) { v2.push_back(i + 1); }
cout << "v2: " << v2 << endl;
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());
//cout << "vTarget: " << vTarget << endl;
cout << "vTarget: ";
for (vector<int>::iterator it = vTarget.begin(); it != itEnd; ++it) { cout << *it << " "; }
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
- 求交集的兩個集合必須是有序數(shù)列
- 目標容器開辟空間需要從兩個容器中取小值
set_intersection
返回值即是交集中最后一個元素的位置
5.6.2 set_union
功能描述:
- 求兩個容器的并集
函數(shù)原型:
-
set_union(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);
// 求兩個容器的并集
// 注意:兩個集合必須是有序數(shù)列
//
beg1
容器1開始迭代器//
end1
容器1結束迭代器//
beg2
容器2開始迭代器//
end2
容器2結束迭代器//
dest
目標容器開始迭代器
示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << " "; }
return cout;
}
void test01() {
vector<int> v1;
for (int i = 0; i < 10; ++i) { v1.push_back(i + 1); }
cout << "v1: " << v1 << endl;
vector<int> v2;
for (int i = -6; i < 5; ++i) { v2.push_back(i + 1); }
cout << "v2: " << v2 << endl;
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());
//cout << "vTarget: " << vTarget << endl;
cout << "vTarget: ";
for (vector<int>::iterator it = vTarget.begin(); it != itEnd; ++it) { cout << *it << " "; }
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
- 求并集的兩個集合必須是有序數(shù)列
- 目標容器開辟空需要兩個容器大小的和
set_union
返回值即是并集中最后一個元素的位置
5.6.3 set_difference
功能描述:
- 求兩個容器的差集
函數(shù)原型:
-
set_difference(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);
// 求兩個容器的差集
// 注意:兩個集合必須是有序數(shù)列
//
beg1
容器1開始迭代器//
end1
容器1結束迭代器//
beg2
容器2開始迭代器//
end2
容器2結束迭代器//
dest
目標容器開始迭代器
示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
ostream &operator<<(ostream &cout, vector<int> &v) {
for (auto it:v) { cout << it << " "; }
return cout;
}
void test01() {
vector<int> v1;
for (int i = 0; i < 10; ++i) { v1.push_back(i + 1); }
cout << "v1: " << v1 << endl;
vector<int> v2;
for (int i = -6; i < 5; ++i) { v2.push_back(i + 1); }
cout << "v2: " << v2 << endl;
vector<int> vTarget;
//目標容器需要提前開辟容器
vTarget.resize(max(v1.size(), v2.size()));
/* v1和v2的差集 */
vector<int>::iterator itEnd = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
//cout << "vTarget: " << vTarget << endl;
cout << "v1和v2的差集: ";
for (vector<int>::iterator it = vTarget.begin(); it != itEnd; ++it) { cout << *it << " "; }
cout << endl;
vTarget.clear();
/* v2和v1的差集 */
itEnd = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), vTarget.begin());
cout << "v2和v1的差集: ";
for (vector<int>::iterator it = vTarget.begin(); it != itEnd; ++it) { cout << *it << " "; }
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:
- 求差集的兩個集合必須是有序數(shù)列
- 目標容器開辟空間需要從兩個容器中取大值
set_difference
返回值即是差集中最后一個元素的位置