1.迭代器的基本概念
作用:迭代器是用于遍历容器元素的对象。
分类:
- 输入迭代器
- 输出迭代器
- 前向迭代器
- 双向迭代器
- 随机访问迭代器
2.迭代器的用法
2.1输入迭代器
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::cout << "Enter integers separated by spaces (Ctrl+D to end): ";
std::istream_iterator<int> input_it(std::cin); //输入迭代器
std::istream_iterator<int> end_of_stream; //输入流结束标志
std::vector<int> vec(input_it, end_of_stream); //从输入流中读取数据并存入向量
std::cout << "You entered: ";
for (const auto& elem : vec) {
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}
2.2输出迭代器
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::cout << "Vector elements: ";
std::ostream_iterator<int> output_it(std::cout, " "); //输出迭代器
std::copy(vec.begin(), vec.end(), output_it); //将向量元素写入到标准输出
std::cout << std::endl;
return 0;
}
2.3前向迭代器
#include <iostream>
#include <forward_list>
int main() {
std::forward_list<int> flist = {1, 2, 3, 4, 5};
std::cout << "Forward list elements: ";
for (auto it = flist.begin(); it != flist.end(); ++it) {
std::cout << *it << " "; // 通过解引用操作符访问元素
}
std::cout << std::endl;
return 0;
}
2.4双向迭代器
#include <iostream>
#include <list>
int main() {
std::list<int> lst = {10, 20, 30, 40, 50};
std::cout << "List elements in forward order: ";
for (auto it = lst.begin(); it != lst.end(); ++it) {
std::cout << *it << " "; // 向前遍历并访问元素
}
std::cout << std::endl;
std::cout << "List elements in reverse order: ";
for (auto it = lst.rbegin(); it != lst.rend(); ++it) {
std::cout << *it << " "; // 向后遍历并访问元素
}
std::cout << std::endl;
return 0;
}
2.5随机访问迭代器
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::cout << "Vector elements: ";
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " "; // 向前遍历并访问元素
}
std::cout << std::endl;
std::cout << "Third element: " << vec[2] << std::endl; // 随机访问第三个元素
return 0;
}
3.常见迭代器的高级操作
3.1std::advance
移动迭代器
#include <iostream>
#include <vector>
#include <iterator>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
auto it = vec.begin();
std::advance(it, 2); // 将迭代器移动两个位置
std::cout << "Element at position 3: " << *it << std::endl;
return 0;
}
3.2std::prev和std::next
获取起一个和后一个迭代器
#include <iostream>
#include <vector>
#include <iterator>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
auto it = vec.begin();
std::advance(it, 2); // 移动到第三个位置
// 使用 std::prev 获取前一个迭代器
auto prev_it = std::prev(it);
std::cout << "Previous element: " << *prev_it << std::endl;
// 使用 std::next 获取后一个迭代器
auto next_it = std::next(it);
std::cout << "Next element: " << *next_it << std::endl;
return 0;
}
标签:std,cout,迭代,STL,int,vec,include
From: https://blog.csdn.net/weixin_52133252/article/details/142789944