未知元素顺序时,如何遍历std::vector中a到b的元素区间?
遍历std::vector中两个指定元素之间的所有元素(不考虑顺序)
你给出的示例代码出现段错误,原因是迭代器越界访问:当a在vector中的位置晚于b时,aIt的位置比bIt靠后,此时aIt != bIt的循环条件会一直成立,aIt++会持续越过vector的末尾,访问非法内存,最终触发段错误。
因为std::vector的迭代器属于随机访问迭代器,支持直接比较大小(</>运算符),我们可以通过确定两个迭代器的前后顺序,来实现安全的遍历。
方案1:遍历两个元素覆盖的完整区间(从位置靠前的到靠后的,包含两端)
这种方式会遍历a和b之间的所有元素(包括a和b),不管两者原本的顺序:
#include <vector> #include <algorithm> #include <iostream> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; int a = 5; int b = 2; auto aIt = std::find(vec.begin(), vec.end(), a); auto bIt = std::find(vec.begin(), vec.end(), b); // 确定区间的起始(靠前的迭代器)和结束(靠后的迭代器) auto start = std::min(aIt, bIt); auto end = std::max(aIt, bIt); // 遍历区间:vector迭代器是左闭右开,所以要遍历到end的下一个位置才能包含end指向的元素 for (auto it = start; it != std::next(end); ++it) { std::cout << *it << std::endl; } return 0; }
运行输出:
2 3 4 5
方案2:从a的位置遍历到b的位置(保留方向)
如果需要严格从a的位置“走到”b的位置——a在b前则正向遍历,a在b后则反向遍历,可以这样实现:
#include <vector> #include <algorithm> #include <iostream> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; int a = 5; int b = 2; auto aIt = std::find(vec.begin(), vec.end(), a); auto bIt = std::find(vec.begin(), vec.end(), b); if (aIt <= bIt) { // a在b前方,正向遍历(包含a和b) for (auto it = aIt; it != std::next(bIt); ++it) { std::cout << *it << std::endl; } } else { // a在b后方,反向遍历(包含a和b) for (auto it = aIt; it != std::prev(bIt); --it) { std::cout << *it << std::endl; } } return 0; }
运行输出:
5 4 3 2
关键注意事项
std::min和std::max可直接比较随机访问迭代器的位置,快速确定区间边界。std::next(it)和std::prev(it)是C++11及以后的迭代器工具函数,比手动it+1/it-1更通用,也适用于非随机访问迭代器。- 必须确保
a和b确实存在于vector中(你已明确此前提),否则std::find会返回vec.end(),后续操作会引发未定义行为。
内容的提问来源于stack exchange,提问作者TheEagle
相关产品推荐
相关产品推荐

