I'm trying to make my own map implementation. 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;
}
}
main code 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;
}
The problem is in the assignment of the values in the map, it tells me
no operators "[]" matches these operands. operand types are MyMap<int, int> [int]
I don't really understand what's wrong with what I wrote because the overloading of the [] operator takes a Key and the Key in this example is set as int and so I pass an int value to the [] operator and the compiler still complains.