定义用于迭代不同容器类型的泛型转换迭代器
Defining a generic transform iterator for iterating over different container types
我有一个类似下面的类:
class ArraySim{
public:
DataStructure* ds;
ArraySim(bool which){
if(true)
ds = new STDMap();
else
ds = new HashMap();
}
value_type& operator[](int idx){
return ds->getValAtIndex(idx);
}
//define a custom iterator type that can be used to iterate over both std::map and boost::unordered //map keys.
}
class DataStructure{
vitrual value_type& getValAtIndex(int idx)=0;
};
class STDMap: public DataStructure{
//Class that wraps a std::map object and implements the virtual method to return the value against a //particular index(key)
};
class HashMap: publlic DataStructure{
//Class that wraps a boost::unordered_map object and implements the virtual method to return the value //against a particular index(key)
}
我已经经历了:通用迭代器和转换迭代器。据我了解,转换迭代器仍然需要您在模板参数中给出底层容器迭代器。那么有没有办法使用转换迭代器围绕映射键定义自定义迭代器类型,同时使其适用于不同类型的映射容器?
如果您使用的是 Boost,则可以使用 any_range
。
typedef any_range<value_type, boost::forward_pass_traversal_tag,
value_type &, std::ptrdiff_t> range;
typedef any_range<value_type, boost::forward_pass_traversal_tag,
const value_type &, std::ptrdiff_t> const_range;
typedef range::iterator iterator;
typedef const_range::const_iterator const_iterator;
virtual iterator begin() = 0;
virtual iterator end() = 0;
virtual const_iterator begin() const = 0;
virtual const_iterator end() const = 0;
您的begin
和end
虚拟只需要构造适当的迭代器:
iterator begin() { return iterator(object.begin()); }
相关文章:
- 给定一个类型,如何派生一个泛型更广泛的类型(例如,用于溢出安全求和)?
- 泛型枚举和其他类型的重载模板函数
- 使用泛型类型推送到堆栈时出现问题
- 以特征类型作为参数的泛型函数回调
- 如何在容器中指定模板化别名的泛型类型
- 具有模板专用化的泛型类型转换
- 将-Wtype限制与类型泛型代码一起使用
- C++存储泛型 T 类型类的向量
- 是否可以使用泛型枚举类型作为函数的参数?
- 如何在C++中返回没有模板的泛型类型?
- 如何在带有约束 (C++) 的函数中使用泛型类型
- 模板函数重载(泛型类型与模板模板类型)选择正确的重载
- 泛型类型别名,它们彼此不兼容
- 从具有泛型返回类型的 crtp 基类调用派生类中的函数
- 获取模板函数/泛型 lambda 的唯一返回类型
- 泛型类型转换
- 重载泛型类型的模板类时检查运算符=时的自赋值
- 为什么C类型泛型表达式不能与C++兼容
- 如何在 Java 中模拟'question mark(?)'类型泛型以C++?
- 构造函数不允许返回类型(泛型链表)