卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章76006本站已运行4317

C++ 自身函数详解及应用:STL 中的算法有哪些常见用法?

stl 算法提供了通用操作,如排序、搜索、修改和转换。常见的算法包括:排序算法:对容器元素排序搜索算法:在容器中查找特定元素修改算法:修改容器中的元素转换算法:将容器中的元素转换为其他容器或数据结构实际案例:std::sort 对数组排序std::find 搜索一个元素std::replace 修改容器中的元素std::transform 将容器转换为另一个容器

C++ 自身函数详解及应用:STL 中的算法有哪些常见用法?

STL 中的算法:常见的用法和实际案例

STL 算法简介

标准模板库 (STL) 提供了一系列用于处理容器和其他数据结构的通用算法。这些算法提供了广泛的常见操作,例如排序、搜索、修改和转换。

立即学习“C++免费学习笔记(深入)”;

常见用法

以下列出了 STL 中一些最常用的算法:

  • 排序算法:用于对容器元素进行排序,例如 std::sort 和 std::stable_sort。
  • 搜索算法:用于在容器中找到特定元素,例如 std::find 和 std::binary_search。
  • 修改算法:用于修改容器中的元素,例如 std::replace 和 std::fill。
  • 转换算法:用于将容器中的元素转换为其他容器或数据结构,例如 std::transform 和 std::copy。

实际案例

使用 std::sort 对数组排序

int my_array[] = {5, 3, 1, 2, 4};
std::sort(my_array, my_array + sizeof(my_array) / sizeof(int));

使用 std::find 搜索一个元素

std::vector<int> my_vector = {5, 3, 1, 2, 4};
std::vector<int>::iterator it = std::find(my_vector.begin(), my_vector.end(), 2);
if (it != my_vector.end()) {
  std::cout << "元素 2 已找到!" << std::endl;
}

使用 std::replace 修改容器中的元素

std::string my_string = "Hello world!";
std::replace(my_string.begin(), my_string.end(), 'l', 'L');
std::cout << my_string << std::endl;

使用 std::transform 将容器转换为另一个容器

std::vector<int> my_vector1 = {5, 3, 1, 2, 4};
std::vector<double> my_vector2;
std::transform(my_vector1.begin(), my_vector1.end(), std::back_inserter(my_vector2), [](int x) { return x * 2; });
卓越飞翔博客
上一篇: C++ 函数库的优缺点有哪些?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏