將std::map重新包裝成一個物件

將std::map重新包裝成一個物件

在std的容器中

iterator是一個很常見的用法

目的是為了讓每個容器有相同的行為模式

這樣到時候因為需求而改變使用的容器時

也不需要修改太多的程式碼

 

但是std::map這個常使用到的容器

他的iterator使用上與其他的std容器有所差別

而且自己本身的操作也比較繁瑣

與其他容器的相容性也不高

所以我在這邊將他獨立成一個物件

在使用上比較方便

 

標頭檔

#ifndef __DICTIONARY__
#define __DICTIONARY__

#include <map>
#include <assert.h>


template <typename KEY, typename VALUE>
class Dictionary
{
public:
typedef std::map<KEY, VALUE> MapType;
typedef std::pair<KEY,VALUE> PairType;

private:
Dictionary(const Dictionary&);
Dictionary& operator=(const Dictionary&);

MapType m_map;
typename MapType::iterator m_it;

public:
Dictionary(){Reset();}
virtual ~Dictionary(){}

/// Add a data if the key is not exist.
bool Add(const KEY& key, const VALUE& val);

/// Is the key in this dictionary?
bool ContainKey(const KEY& key)
{return m_map.find(key)!=m_map.end();}

/// Get the value by the key.
VALUE& operator[](const KEY& key);

/// Get the value by the key. If the key is exist, it will return true.
bool TryGet(const KEY& key, VALUE& val);

/// How many data are in this dictionary.
int Size()
{return m_map.size();}

/// Remove the data by the key.
/// Don't use it in the iterator mode.
bool RemoveByKey(const KEY& key);

/// Set the offset to first iterator.
void Reset()
{ m_it = m_map.begin(); }

/// Get the key in the current iterator.
KEY GetCurrentKey()
{return (*m_it).first;}

/// Get the value in the current iterator.
VALUE GetCurrentValue()
{return (*m_it).second;}

/// Move the offset to next iterator.
bool Next();

/// Remove the data which was dicated by current iterator.
void RemoveCurrentData();
};
#endif /*__DICTIONARY__*/

 

實作

template <typename KEY, typename VALUE>
void Dictionary<KEY, VALUE>::RemoveCurrentData()
{
typename MapType::iterator _itRemove;
_itRemove = m_it;
m_it++;
m_map.erase(_itRemove);
}


template <typename KEY, typename VALUE>
bool Dictionary<KEY, VALUE>::Next()
{
m_it++;
if(m_it==m_map.end())
return false;

return true;
}


template <typename KEY, typename VALUE>
VALUE& Dictionary<KEY, VALUE>::operator[](const KEY& key)
{
assert(ContainKey(key));
return m_map[key];
}


template <typename KEY, typename VALUE>
bool Dictionary<KEY, VALUE>::RemoveByKey(const KEY& key)
{
if(!ContainKey(key))
return false;

m_map.erase(key);
return true;
}


template <typename KEY, typename VALUE>
bool Dictionary<KEY, VALUE>::TryGet(const KEY& key, VALUE& val)
{
if(!ContainKey(key))
return false;

val = m_map[key];
return true;
}


template <typename KEY, typename VALUE>
bool Dictionary<KEY, VALUE>::Add(const KEY& key, const VALUE& val)
{
if(ContainKey(key))
return false;

m_map.insert(PairType(key, val));
return true;
}