一般的正向集合遍历
1. for/index/size模式
for(int i = 0; i < collection.size(); ++i) {
std::cout << collection[i] << std::endl;
}
弊端: 只适合std::vector
这种可以通过下标随机O(1)时间访问的集合类型
2. for/begin/end 模式
for(auto it = collection.begin(); it != collection.end(); ++it) {
std::cout << *it << std::endl;
// std::cout << it->first << ", " << it->second << std::endl;
}
这种适合大多数的集合遍历模式
3. for/in 模式(for/begin/end
模式的精简版)
for(auto& item: collection) {
std::cout << item << std::endl;
// std::cout << item.first << ", " << item.second << std::endl;
}
这种写法属于C++11
开始出现的语法糖,只要集合(包括标准库的集合和用户自定义的集合甚至伪集合)能使用for/begin/end模式
的遍历方式就能使用这种语法糖模式
如果想反向遍历怎么办?
可能的思路
- 将集合先反转再遍历:可能集合被限制为常量不可反转自身,受限
- 将集合反向拷贝再遍历: 集合数量比较庞大时,会占用大量内存,慎用
- 反向迭代器(rbegin+rend): 我觉得可以,推荐
反向迭代器
示例代码:
for(auto it = collection.rbegin(); it != collection.rend(); ++it) {
std::cout << *it << std::endl;
// std::cout << it->first << ", " << it->second << std::endl;
}
其实用法和for/begin/end模式
几乎一样,只是需要使用rbegin
和rend
来代替begin
和end
, rbegin()
表示反向迭代器的开始, 也就是正向的末尾, rend()
表示反向迭代器的末尾也就是正向迭代器的开始
能不能使用语法糖?
直接使用当然不行,但并不表示我们不能使用
回想下上面的一句很关键的话: 只要集合(包括标准库的集合和用户自定义的集合甚至伪集合)能使用(for/begin/end模式)的遍历方式就能使用这种语法糖模式
解决方案
把当前集合rbegin
和rend
接口调用转换成另外一个对象的 begin()
和end()
接口调用, 并且返回的迭代器是不变的
具体实现
示例代码
namespace oyoung {
template<typename T>
struct CollectionReverse {
using iterator = typename T::reverse_iterator;
using const_iterator = typename T::const_reverse_iterator;
explicit CollectionReverse(T& col)
: _M_collection(col) {}
iterator begin() {
return _M_collection.rbegin();
}
const_iterator begin() const {
return _M_collection.rbegin();
}
iterator end() {
return _M_collection.rend();
}
const_iterator end() const {
return _M_collection.rend();
}
private:
T & _M_collection;
};
template<typename T>
CollectionReverse<T> reverse(T& col) {
return CollectionReverse<T>(col);
}
}
如何使用呢?
#include <map>
#include <set>
#include <list>
#include <vector>
#include <iostream>
int main(int argc, const char * argv[]) {
std::vector<int> vi {0,1, 2, 3, 4, 5};
std::list<int> li {10, 11, 12, 12, 14, 15};
std::map<int, int> mii {
{0, 10}, {1, 11}, {2, 12}, {3, 13}, {4,14}, {5,15}
};
std::set<int> si {0, 1, 2, 3, 4, 4, 5, 5};
std::cout << "reversed vector: ";
for(auto i: oyoung::reverse(vi)) {
std::cout << i << ' ';
}
std::cout << std::endl;
std::cout << "reversed list: ";
for(auto i: oyoung::reverse(li)) {
std::cout << i << ' ';
}
std::cout << std::endl;
std::cout << "reversed map: ";
for(auto pair: oyoung::reverse(mii)) {
std::cout << '(' << pair.first << ": " << pair.second << "),";
}
std::cout << std::endl;
std::cout << "reversed set: ";
for(auto i: oyoung::reverse(si)) {
std::cout << i << ' ';
}
std::cout << std::endl;
return 0;
}
输出结果对不对呢? 😉
reversed vector: 5 4 3 2 1 0
reversed list: 15 14 12 12 11 10
reversed map: (5: 15),(4: 14),(3: 13),(2: 12),(1: 11),(0: 10),
reversed set: 5 4 3 2 1 0