C++ STL 中的非变易算法(Non-modifying Algorithms)是指那些不会修改容器内容的算法,是C++提供的一组模板函数,该系列函数不会修改原序列中的数据,而是对数据进行处理、查找、计算等操作,并通过迭代器实现了对序列元素的遍历与访问。由于迭代器与算法是解耦的,因此非变易算法可以广泛地应用于各种容器上,提供了极高的通用性和灵活性。
这些算法都是在头文件 <algorithm>
中定义的,其主要包括以下几类非变易算法:
- 查找算法:
find()
:在容器中查找指定值的元素,并返回第一个匹配的位置。find_if()
:根据给定的条件(函数对象或谓词)查找容器中满足条件的元素,并返回第一个匹配的位置。count()
:计算容器中等于指定值的元素个数。
- 遍历算法:
for_each()
:对容器中的每个元素应用指定的函数。accumulate()
:计算容器中元素的累加和。count_if()
:计算满足给定条件的元素个数。
- 排序算法(不属于查找和遍历,但不会修改元素内容):
sort()
:对容器中的元素进行排序,默认是按升序排列。partial_sort()
:对容器中的部分元素进行排序。stable_sort()
:稳定地对容器中的元素进行排序。
通过它们可以高效地操作容器中的元素,这为C++开发者提供了更方便和安全的方式来处理数据,减少了代码的复杂性和错误的可能性。通过合理地运用这些算法,可以极大地提高程序的执行效率和代码的可读性。
7.1 遍历容器元素
For_each 算法函数,用于对序列中的每个元素执行指定操作。for_each的用法如下:
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f);
其中,first、last
是迭代器,表示待执行操作的序列的范围;f是一个函数对象,用于指定要执行的操作。调用for_each
函数后,将会对[first, last]
区间内的每个元素调用一次f函数,并将该元素作为f函数的参数。for_each
函数返回一个函数对象f。
该函数用于对容器的元素进行循环操作,常用于元素遍历。
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
struct MyPrint{
int count; // 设置元素计数
MyPrint(){ count = 0; } // 初始化元素
void operator()(int x) // 重载小括号
{
cout << x << endl;
count++;
}
};
int main(int argc, char* argv[])
{
list<int> ls {1,2,3,4,5,6,7,8,9};
MyPrint p = for_each(ls.begin(), ls.end(), MyPrint());
cout << "Link Count: " << p.count << endl;
system("pause");
return 0;
}
7.2 普通查找容器元素
Find 算法函数,用于查找序列中指定值的第一个元素,并返回该元素的迭代器。find的用法如下:
template<class InputIterator, class T>
InputIterator find(InputIterator first, InputIterator last, const T& value);
其中,first、last
是迭代器,表示待查找的序列的范围;value
是需要查找的元素的值。调用find
函数后,将会在[first, last]
区间中查找第一个等于value
的元素,并将该元素的迭代器作为函数返回值返回。如果未找到等于value
的元素,则函数将返回last。
该算法用于查找某个值等于某值得元素,它在迭代区间是(frist,last)
之间寻找value
值。
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
list<int> ls{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
list<int>::iterator it = find(ls.begin(), ls.end(),6);
if (it != ls.end())
{
cout << "找到了元素" << endl;
cout << "前一个元素: " << *(--it) << endl;
}
system("pause");
return 0;
}
7.3 类查找容器元素
Find 算法函数,用于查找序列中指定值的第一个元素,并返回该元素的迭代器。find的用法如下:
template<class InputIterator, class T>
InputIterator find(InputIterator first, InputIterator last, const T& value);
其中,first、last
是迭代器,表示待查找的序列的范围;value
是需要查找的元素的值。调用find
函数后,将会在[first, last]
区间中查找第一个等于value
的元素,并将该元素的迭代器作为函数返回值返回。如果未找到等于value
的元素,则函数将返回last。
该算法不仅可以查询普通数据结构,还可以查询结构与类中数据,如下则是一段演示案例;
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Person
{
public:
string m_name;
int m_age;
public:Person(string name, int age){
this->m_name = name;
this->m_age = age;
}
public: bool operator==(const Person &p){
// 重载 == 实现遍历数据
if (this->m_name == p.m_name && this->m_age == p.m_age)
return true;
return false;
}
};
int main(int argc, char* argv[])
{
vector<Person> var;
Person p1("aaa", 10);