c++ 遍历方法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
在C++中,遍历数据结构(如数组、向量、链表等)通常可以使用循环结构或迭代器(Iterator)来实现。
以下是一些常见的遍历方法:
### 1. 数组的遍历:
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
// 使用for循环
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// 使用范围-based for循环(C++11及以上版本支持)
for (int element : arr) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
}
### 2. 向量(vector)的遍历:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用迭代器
for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// 使用范围-based for循环(C++11及以上版本支持)
for (int element : vec) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
}
### 3. 链表的遍历:
#include <iostream>
// 链表节点定义
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
int main() {
// 创建一个简单的链表
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
// 使用while循环遍历链表
ListNode* current = head;
while (current != nullptr) {
std::cout << current->val << " ";
current = current->next;
}
std::cout << std::endl;
return 0;
}
这些是常见的遍历方法,具体的选择取决于数据结构的类型以及个人偏好。
在C++11及以上版本中,推荐使用范围-based for循环,因为它更加简洁和易读。