首页 > 技术文章 > 自己动手实现线性映射,哈希映射

chess 2015-10-03 11:03 原文

一个简单的线性映射:

#include<vector>
#include<iostream>
using namespace std;
template<class Key,class Value>
class LinearMap
{
public:
    LinearMap(int size = 101) :arr(size)
    {
        current_size = 0;
    }

    void Put(const Key&k, const Value&v)
    {
        arr[current_size] = DataEntry(k, v);
        ++current_size;
    }
    Value Get(const Key&k)
    {
        for (int i = 0; i < current_size; ++i)
        {
            if (arr[i].key == k)
                return arr[i].value;
        }
        return Value();
    }
private:
    struct DataEntry{
        Key key;
        Value value;
        DataEntry(const Key&k = Key(), const Value&v = Value()) :key(k), value(v){};
    };
    vector<DataEntry> arr;
    int current_size;
};
int main()
{
    LinearMap<string, int> lm;
    lm.Put("tom", 99);
    lm.Put("Jack", 88);
    lm.Put("ly", 77);
    cout << lm.Get("Jack") << endl;
    return 0;
}
View Code

 

推荐阅读