阻止直接访问std :: map键 [英] Prevent direct access to std::map keys

查看:116
本文介绍了阻止直接访问std :: map键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想包装一个 std :: map ,所以客户端不知道我将它们的正整数键实际存储为负整数。我需要允许遍历类并访问元素。

I would like to wrap a std::map so the client is unaware that I am storing their positive integer keys actually as negative integers. I need to allow iterating over the class and accessing the elements.

我想到了这个类:

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()环。

However, I don't like having two methods to iterate, first getFirstElement() outside of the loop and then getNextElement() within the loop.

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

Is there a way to achieve this so the client can write neater code?

推荐答案

我想你想要这个:

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

在获得元素之前判断它是否为null。

To judge whether it is 'null', before you get elements.

这篇关于阻止直接访问std :: map键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆