simplemap.h

来自「C++&datastructure书籍源码,以前外教提供现在与大家共享」· C头文件 代码 · 共 66 行

H
66
字号
#ifndef _SIMPLEMAP_H
#define _SIMPLEMAP_H

#include "tvector.h"

// simple map, supports (for map m):
//    m.insert(Key,Value);
//    v = m.getValue(k);    // returns default Value() if k not found


template <class Key,class Value> class SimpleMapIterator;

template <class Key, class Value>
class SimpleMap
{
  public:
    SimpleMap()
    { }
    void insert(const Key& k, const Value& v)
    {
        myKeys.push_back(k);
        myValues.push_back(v);
    }
    Value getValue(const Key& key) const
    {   for(int k=0; k < myKeys.size(); k++)
        {   if (myKeys[k] == key) return myValues[k];
        }
        return Value();
    }
    
    
    friend class SimpleMapIterator<Key,Value>;
    
  private:
    tvector<Key>   myKeys;
    tvector<Value> myValues;
};


template <class Key,class Value>
class SimpleMapIterator
{
  public:
    SimpleMapIterator(const SimpleMap<Key,Value>& map)
      : myMap(map),
        myIndex(-1)
    { }
    void Init()
    {   myIndex = 0;
    }
    bool HasMore()
    {   return myIndex < myMap.myKeys.size();
    }
    void Next()
    {   myIndex++;
    }
    Key Current()
    {   return myMap.myKeys[myIndex];
    }
  private:
    const SimpleMap<Key,Value>& myMap;
    int              myIndex;
};

#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?