首页 > 后端开发 > C++ > 正文

C++ 函数的 STL 函数有哪些用于泛型算法?

WBOY
发布: 2024-10-07 12:09:01
原创
1141人浏览过

stl 函数是 c++++ 泛型算法函数,用于执行常见数据操作。它们包括:find:查找元素count:计算元素出现次数transform:转换元素min_element/max_element:查找最大/最小元素sort:排序容器元素

C++ 函数的 STL 函数有哪些用于泛型算法?

STL 函数:C++ 函数中用于泛型算法

标准模板库(STL)提供了广泛的泛型算法函数,可对各种数据结构执行常见操作,而无需编写重复性代码。本文重点介绍一些最常用的 STL 函数及其在实战中的应用。

1. find: 查找容器中特定元素的第一个匹配项。

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

#include <vector>
#include <algorithm>

using namespace std;

int main() {
  vector<int> numbers = {1, 2, 3, 4, 5, 6, 7};

  int target = 4;
  auto it = find(numbers.begin(), numbers.end(), target);

  if (it != numbers.end()) {
    cout << "Found " << target << " at index " << (it - numbers.begin()) << endl;
  } else {
    cout << "Target not found" << endl;
  }

  return 0;
}
登录后复制

2. count: 计算容器中指定元素出现的次数。

#include <map>
#include <algorithm>

using namespace std;

int main() {
  map<string, int> word_count;
  word_count.insert({"apple", 2});
  word_count.insert({"banana", 3});
  word_count.insert({"cherry", 1});

  int occurrences = count(word_count.begin(), word_count.end(), pair<string, int>("banana", 3));

  cout << "Occurrences of (banana, 3): " << occurrences << endl;

  return 0;
}
登录后复制

3. transform: 将容器中的每个元素转换为新容器中的新值。

#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

int main() {
  vector<double> numbers = {1.1, 2.2, 3.3, 4.4, 5.5};

  vector<int> rounded_numbers;
  transform(
    numbers.begin(), numbers.end(), back_inserter(rounded_numbers),
    [](double d) { return static_cast<int>(round(d)); });

  for (auto n : rounded_numbers) {
    cout << n << " ";
  }
  cout << endl;

  return 0;
}
登录后复制

4. min_element/max_element: 找出容器中最小的或最大的元素。

#include <vector>
#include <algorithm>

using namespace std;

int main() {
  vector<char> characters = {'a', 'b', 'c', 'd', 'e'};

  auto smallest = min_element(characters.begin(), characters.end());
  auto largest = max_element(characters.begin(), characters.end());

  cout << "Smallest character: " << *smallest << endl;
  cout << "Largest character: " << *largest << endl;

  return 0;
}
登录后复制

5. sort: 对容器中的元素进行排序。

#include <vector>
#include <algorithm>

using namespace std;

int main() {
  vector<int> numbers = {8, 1, 3, 7, 5, 9, 6};

  sort(numbers.begin(), numbers.end());

  for (auto n : numbers) {
    cout << n << " ";
  }
  cout << endl;

  return 0;
}
登录后复制

这些只是 STL 提供的众多泛型算法函数中的一部分。它们提供了强大的工具,可以极大地简化数据操作任务,并避免重复编码。

以上就是C++ 函数的 STL 函数有哪些用于泛型算法?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号