C++ 中常用的 STL

标准模板库 (STL) 是 C++ 标准库中一个强大的组件,它提供了各种通用数据结构和算法。STL 旨在提高代码的可重用性、效率和可读性。本文将介绍 C++ 中一些常用的 STL,并提供代码示例。

容器

容器是用于存储和组织数据的对象。STL 中提供了以下几种容器:

  • vector:一个动态数组,可以高效地添加和删除元素。
#include <vector>

int main() {
  std::vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);

  for (int i : v) {
    std::cout << i << " ";
  }
  std::cout << std::endl;

  return 0;
}
  • list:一个双向链表,可以高效地插入和删除元素。
#include <list>

int main() {
  std::list<int> l;
  l.push_back(1);
  l.push_back(2);
  l.push_back(3);

  for (int i : l) {
    std::cout << i << " ";
  }
  std::cout << std::endl;

  return 0;
}
  • set:一个无序集合,其中元素是唯一的。
#include <set>

int main() {
  std::set<int> s;
  s.insert(1);
  s.insert(2);
  s.insert(3);

  for (int i : s) {
    std::cout << i << " ";
  }
  std::cout << std::endl;

  return 0;
}
  • map:一个关联容器,其中键与值相关联。
#include <map>

int main() {
  std::map<int, std::string> m;
  m[1] = "one";
  m[2] = "two";
  m[3] = "three";

  for (auto it = m.begin(); it != m.end(); ++it) {
    std::cout << it->first << " => " << it->second << std::endl;
  }

  return 0;
}

算法

STL 还提供了各种算法,用于对容器中的元素进行操作。以下是一些常用的算法:

  • sort:对容器中的元素进行排序。
#include <algorithm>
#include <vector>

int main() {
  std::vector<int> v = {3, 1, 2};
  std::sort(v.begin(), v.end());

  for (int i : v) {
    std::cout << i << " ";
  }
  std::cout << std::endl;

  return 0;
}
  • find:在容器中查找特定元素。
#include <algorithm>
#include <vector>

int main() {
  std::vector<int> v = {3, 1, 2};
  std::vector<int>::iterator it = std::find(v.begin(), v.end(), 2);

  if (it != v.end()) {
    std::cout << "Found 2 at index " << it - v.begin() << std::endl;
  } else {
    std::cout << "2 not found" << std::endl;
  }

  return 0;
}
  • count:计算容器中特定元素出现的次数。
#include <algorithm>
#include <vector>

int main() {
  std::vector<int> v = {3, 1, 2, 2};
  int count = std::count(v.begin(), v.end(), 2);

  std::cout << "2 appears " << count << " times" << std::endl;

  return 0;
}

迭代器

迭代器是用于遍历容器中元素的特殊对象。STL 提供了以下几种迭代器:

  • begin:返回容器的第一个元素的迭代器。
  • end:返回容器的最后一个元素的迭代器。
  • rbegin:返回容器的第一个元素的逆向迭代器。
  • rend:返回容器的最后一个元素的逆向迭代器。

代码演示:

// 使用迭代器遍历 vector
for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
  std::cout << *it << " ";
}

结论

STL 是 C++ 中一个强大的工具,它提供了各种通用数据结构和算法。通过使用 STL,开发人员可以提高代码的可重用性、效率和可读性。本文介绍了一些常用的 STL,但还有许多其他有用的组件可供探索。

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慢跑的平头哥

你的鼓励是我创作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值