【发布时间】:2019-01-25 13:41:47
【问题描述】:
我想包装一个std::map,所以客户不知道我将他们的正整数键实际上存储为负整数。我需要允许遍历类并访问元素。
我想出了这门课:
template<class K, class V>
class Container
{
public:
Container(){}
void insert(const K& key, const V& value)
{
_map[key] = value;
}
bool getFirstElement(K& key, V& value)
{
if (false == _map.empty())
{
_iter = _map.begin();
value = _iter->second;
key = std::abs(_iter->first);
return true;
}
return false;
}
bool getNextElement(K& key, V& value)
{
++_iter;
if (_iter != _map.end())
{
key = std::abs(_iter->first); // I modify the key
value = _iter->second;
return true;
}
return false;
}
private:
typename std::map<K, V>::iterator _iter; // Caches client's position whilst iterating
std::map<K, V> _map;
};
用法是:
int main()
{
Container<int, int> o;
o.insert(-1, 100);
o.insert(-2, 200);
o.insert(-3, 300);
int key;
int value;
o.getFirstElement(key, value);
std::cout << "key: " << key << " val: " << value << std::endl;
while (o.getNextElement(key, value))
{
std::cout << "key: " << key << " val: " << value << std::endl;
}
}
但是,我不喜欢有两种迭代方法,首先是循环外的getFirstElement(),循环内的然后 getNextElement()。
有没有办法实现这一点,以便客户端可以编写更整洁的代码?
【问题讨论】:
-
getFirstElement被声明为返回bool,但不包含return语句。对它的任何调用都会表现出未定义的行为。 -
您可以实现自定义迭代器以配合您的自定义容器。
-
@IgorTandetnik 抱歉,我在写完问题后在 IDE 中更改了它。现已更新。
-
@IgorTandetnik,你能举个例子吗?
标签: c++ dictionary stl iterator