要遍历 stl 容器,可以使用容器的 begin() 和 end() 函数获取迭代器范围:向量:使用 for 循环遍历迭代器范围。链表:使用 next() 成员函数遍历链表元素。映射:获取键值对迭代器,使用 for 循环遍历。
如何遍历 C++ STL 容器
遍历 C++ 标准模版库 (STL) 容器是程序员日常工作中必不可少的一项任务。STL 提供了一系列预定义数据结构,如向量、链表和映射,每个结构都有自己的遍历方法。
遍历 STL 矢量要遍历一个矢量,我们可以使用 begin() 和 end() 函数获得迭代器范围:
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
// 使用基于范围的 for 循环
for (int num : v) {
std::cout << num << " ";
}
std::cout << std::endl;
// 使用迭代器
for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
输出:
1 2 3 4 5
1 2 3 4 5
遍历 STL 链表要遍历一个链表,我们可以使用链表的 front() 和 back() 函数以及该链表的 next() 成员函数:
#include <list>
int main() {
std::list<int> l = {1, 2, 3, 4, 5};
// 使用基于范围的 for 循环
for (int num : l) {
std::cout << num << " ";
}
std::cout << std::endl;
// 使用迭代器
std::list<int>::iterator it = l.begin();
while (it != l.end()) {
std::cout << *it << " ";
it = it->next();
}
std::cout << std::endl;
return 0;
}
输出:
1 2 3 4 5
1 2 3 4 5
遍历 STL 映射要遍历一个映射,我们可以使用映射的 begin() 和 end() 函数获取键值对的迭代器:
#include <map>
int main() {
std::map<std::string, int> m = {{"Apple", 1}, {"Banana", 2}, {"Cherry", 3}};
// 使用基于范围的 for 循环
for (auto const& [key, value] : m) {
std::cout << key << ": " << value << std::endl;
}
std::cout << std::endl;
// 使用迭代器
for (std::map<std::string, int>::iterator it = m.begin(); it != m.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
输出:
Apple: 1
Banana: 2
Cherry: 3
Apple: 1
Banana: 2
Cherry: 3
以上就是如何遍历C++ STL容器?的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论