c++oding="utf-8" ?>
在 c++ stl 中,多态函数允许通用代码处理不同数据类型对象或容器。这些函数包括:find()、find_if()、push_back()、insert()、begin()、end() 和函数对象。通过使用多态函数和函数对象,我们可以在类型无关的情况下执行操作,例如查找满足特定条件的元素并打印其平方。

C++ STL 中的多态函数
在标准模板库 (STL) 中,多态函数是为处理具有不同数据类型参数的对象或容器而设计的。它们允许使用通用代码来实现与类型无关的操作。
常见的 STL 多态函数:
-
算法:
- find()
- find_if()
- count()
- count_if()
-
容器:
- push_back()
- insert()
- erase()
- size()
-
迭代器:
- begin()
- end()
-
函数对象:
- greater()
- less()
实战案例:
查找所有大于 10 的元素并打印其平方:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool greater_than_ten(int x) {
return x > 10;
}
int main() {
vector<int> v = {1, 2, 5, 12, 9, 14};
// 查找所有大于 10 的元素并存储在 result 中
vector<int> result;
copy_if(v.begin(), v.end(), back_inserter(result), greater_than_ten);
// 打印 result 中元素的平方
for (auto& x : result) {
cout <p><strong>输出:</strong></p>
<pre class="brush:php;toolbar:false;">144
196
要点:
-
copy_if()是一个多态算法,用于从源范围(v)复制满足谓词(greater_than_ten)的元素。 -
back_inserter()是一种迭代器适配器,负责将元素插入目标容器(result)。 -
greater_than_ten()是一个函数对象,实现了比较运算以过滤大于 10 的元素。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











