c++ - 定义通用变换迭代器以迭代不同的容器类型

标签 c++ boost iterator

我的类(class)如下:

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)
} 

我经历过:Generic IteratorTransform Iterator .据我了解,转换迭代器仍然需要您在模板参数中提供底层容器迭代器。那么有没有一种方法可以使用转换迭代器围绕 map 键定义自定义迭代器类型,同时使其适用于不同类型的 map 容器?

最佳答案

如果您使用的是 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;

您的beginend 虚拟只需要构造适当的迭代器:

iterator begin() { return iterator(object.begin()); }

关于c++ - 定义通用变换迭代器以迭代不同的容器类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13643384/

相关文章:

c++ - STL 中 next_permutation 的 Python 实现

python - 如何在 python 中循环遍历 .csv 文件

c++ - 在 C++ 中添加到哈希表?

c++ - 使用 Boost 条件变量的死锁;指针不在线程之间更新?

c++ - boost log 打印源代码文件名和行号

ruby - 重试语句在 Ruby 中如何工作?

c++ - 动态堆栈分配(来自 Thinking in C++)

c++ - 如何指定用于保存模型的设备

c# - 在 C# 应用程序性能中访问 C++ 代码

c++ - 无论编码如何,从 wifstream 中提取正确的文本