我有一个类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 d
在insert
功能现在将被忽略。下面的代码应该仍然有效,其中 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 迭代器并提供 first
和 second
成员。基本上你的 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/