第四十八节 C++ STL 算法
程序员文章站
2022-03-06 11:49:14
...
STL算法:
1 头文件 #include <algorithm>
2 算法通常与迭代器和函数对象一起使用
仅举几个例子。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
/*1 函数模板:为了打印不同类型的内容*/
template <typename T1>
void DisplayContent(const T1 input) {
int index = 0;
cout << " data: ";
for (auto Iterator = input.begin(); Iterator != input.end(); ++Iterator) {
index = std::distance(input.begin(), Iterator);
cout << " " << *Iterator;
}
cout << endl;
}
int main()
{
/*1 find(), find_if()*/
cout << "1 find(), find_if() : " << endl;
std::vector <int> intVector;
for (int index = 0; index < 4; ++index) {
intVector.push_back(index+4);
intVector.push_back(index + 4);
}
DisplayContent(intVector);
auto iElement = find(intVector.begin(), intVector.end(), 6); //使用find()查找第一个指定值6
if (iElement != intVector.end()) {
cout << " find the value = " << *iElement << endl;
}
auto lambdaFormat1 = [] (const int& value) {
return (value % 2 == 0);
};
auto iElement2 = find_if(intVector.begin(), intVector.end(), lambdaFormat1); //使用find_if()查找第一个满足lambdaFormat1条件的值
if (iElement2 != intVector.end()) {
cout << " find_if the value = " << *iElement2 << endl;
}
/*2 count(), count_if()*/
cout << "2 count(), count_if() : " << endl;
int num = count(intVector.begin(), intVector.end(), 6); //使用count()查找6的个数
cout << " the num1 = " << num << endl;
int num2 = count_if(intVector.begin(), intVector.end(), lambdaFormat1); //使用count_if()查找满足条件的个数
cout << " the num2 = " << num2 << endl;
return 0;
}
1 find(), find_if() :
data: 4 4 5 5 6 6 7 7
find the value = 6
find_if the value = 4
2 count(), count_if() :
the num1 = 2
the num2 = 4