gpt4 book ai didi

c++ - 防止直接访问 std::map 键

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:40:31 24 4
gpt4 key购买 nike

我想包装一个 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() ,然后是 then getNextElement()在循环内。

有没有办法实现这一点,以便客户可以编写更整洁的代码?

最佳答案

do 
{
std::cout << "key: " << key << " val: " << value << std::endl;
}while (o.getNextElement(key, value));

所以所有的操作都在这样的循环中。

关于c++ - 防止直接访问 std::map 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51913588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com