地图实施

时间:2014-10-09 15:43:52

标签: c++ map

我试图制作自己的地图实施。 MyMap.h:

#pragma once

#include <set>
#include <list>
#include <utility>

template <class Key, class Value> class MyMap
{
public:
    MyMap();
    ~MyMap();
    int count(Key&);
    Value& operator[](Key&);
private:
    std::set<Key> m_keys;
    std::list<std::pair<Key, Value*> > m_kvList;
};

MyMap.cpp

#include "stdafx.h"
#include "MyMap.h"

MyMap<class Key, class Value>::MyMap()
{

}


MyMap<class Key, class Value>::~MyMap()
{

}

int MyMap<class Key, class Value>::count(Key& k)
{
    if (m_keys.find(k) != m_keys.end())
        return 1;
    return 0;
}

Value& MyMap<class Key, class Value>::operator[](Key& k)
{
    if (count(k) == 0)
    {
        m_keys.insert(k);
        Value* pValue;
        std::pair<Key, Value*> kvPair(k, pValue);
        m_kvList.push_back(kvPair);
        return *pValue;
    }
    std::list<std::pair<Key, Value*> >::const_iterator it;
    for (it = m_kvList.begin(); it != m_kvList.end(); it++)
    {
        if ((*it).first == k)
            return *(*it).second;
    }
}

主要代码cpp

#include "stdafx.h"
#include <iostream>
#include <string>
#include "MyMap.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    MyMap<int, int> m1;
    m1[3] = 60;
    m1[1] = 30;
    m1[2] = 95;
    return 0;
}

问题在于在地图中赋值,它告诉我

no operators "[]" matches these operands. operand types are MyMap<int, int> [int]

我真的不明白我写的内容有什么问题,因为[]运算符的重载需要一个Key,而这个例子中的Key设置为int,因此我将一个int值传递给[]运算符和编译器仍然抱怨。

0 个答案:

没有答案
相关问题