c++ - 如何调整集合迭代器使其表现得像 map 迭代器?

标签 c++ stl iterator encapsulation

我有一个类Foo包含 map并提供 begin()end()迭代它的函数:

class Foo {
  typedef std::map<int, double> Container;
  typedef Container::const_iterator const_iterator;
  Container c_;
 public:
  const_iterator begin() const { return c_.begin(); }
  const_iterator end() const { return c_.end(); }
  void insert(int i, double d) { c_[i] = d; }
  // ...

};

现在我想在内部从 std::map<int, double> 更改它只是一个 std::set<int> ,但我不想破坏任何客户端代码。

所以 double dinsert功能现在将被忽略。下面的代码应该仍然有效,其中 it->second现在将永远是 0.0 :

Foo foo;
for(Foo::const_iterator it = foo.begin(); it != foo.end(); ++it) {
  std::cout << it->first << " " << it->second << std::endl;
}

如何在 Foo 中进行这些更改?类(class)?

换句话说,我如何提供 Foo::const_iterator适应新的内部std::set<int>::const_iterator表现得像老std::map<int,double>::const_iterator

更新:我想摆脱 map 的原因是内存效率。我有数百万Foo实例并且无力存储 double他们的值(value)观。

最佳答案

会用

std::set<std::pair<int, double> >

这种可比性还不够吗?

如果失败,您始终可以编写自己的迭代器,它包装 std::list 迭代器并提供 firstsecond 成员。基本上你的 operator++ 会在真正的迭代器等上调用 operator++ 并且取消引用运算符可以返回一个临时的 std::pair (按值)或对迭代器本身内的 std::pair 的引用(如果你的遗产代码可以处理)。

更新,稍微做作的示例,可能会根据您的情况起作用:

#include <iostream>
#include <set>

class Foo {
  typedef std::set<int> Container;
  typedef Container::const_iterator legacy_iterator;
  Container c_;

  // legacy iterator doesn't have a virtual destructor (probably?), shouldn't
  // be a problem for sane usage though
  class compat_iterator : public legacy_iterator {
  public:
     compat_iterator(const legacy_iterator& it) : legacy_iterator(it) {
     }

     const std::pair<int,double> *operator->() const {
        static std::pair<int,double> value;
        value = std::make_pair(**this, 0.0);
        // Not meeting the usual semantics!
        return &value;
     }
  };
 public:
  typedef compat_iterator const_iterator;

  const_iterator begin() const { return c_.begin(); }
  const_iterator end() const { return c_.end(); }

};



int main() {

  Foo foo;
  for(Foo::const_iterator it = foo.begin(); it != foo.end(); ++it) {
     std::cout << it->first << " " << it->second << std::endl;
  }

}

关于c++ - 如何调整集合迭代器使其表现得像 map 迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4165471/

相关文章:

c++ - 添加typename导致程序编译失败

c++ Lock类骨架

c++ - 扩展 vector 迭代器以访问包含的类/结构的数据成员

rust - 如何解决预期的 `:` ,发现关键字 `self` ?

java - 为什么 iterator.next() 每次都返回相同的项目?

C++ 生产者消费者陷入死锁

c++ - 在二维迷宫中寻找路径

c++ - 正则表达式,找不到匹配项

c++ - in 或 for_each 哪个更适合 each?

c++ - 如何将指针的关系比较变成错误?