九口袋网站建设,网页小游戏开发,网络推广专员是干什么的,如何让网站速度快标准模板库 (STL) 是 C 标准库中一个强大的组件#xff0c;它提供了各种通用数据结构和算法。STL 旨在提高代码的可重用性、效率和可读性。本文将介绍 C 中一些常用的 STL#xff0c;并提供代码示例。
容器
容器是用于存储和组织数据的对象。STL 中提供了以下几种容器…标准模板库 (STL) 是 C 标准库中一个强大的组件它提供了各种通用数据结构和算法。STL 旨在提高代码的可重用性、效率和可读性。本文将介绍 C 中一些常用的 STL并提供代码示例。
容器
容器是用于存储和组织数据的对象。STL 中提供了以下几种容器
vector一个动态数组可以高效地添加和删除元素。
#include vectorint main() {std::vectorint 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 listint main() {std::listint 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 setint main() {std::setint 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 mapint main() {std::mapint, 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 vectorint main() {std::vectorint 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 vectorint main() {std::vectorint v {3, 1, 2};std::vectorint::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 vectorint main() {std::vectorint 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::vectorint::iterator it numbers.begin(); it ! numbers.end(); it) {std::cout *it ;
}结论
STL 是 C 中一个强大的工具它提供了各种通用数据结构和算法。通过使用 STL开发人员可以提高代码的可重用性、效率和可读性。本文介绍了一些常用的 STL但还有许多其他有用的组件可供探索。