I am trying to implementing a map using vector. I am stuck in the find functionality since I am using a struct with key and value and while searching user will only provide the key and I have to use a dummy in the value field which I currently cannot do since it is a template.
Help is appreciated. :)
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
//coll.insert(std::make_pair("otto",22.3));
using namespace std;
template<class T1, class T2>
class MyMap
{
protected:
struct mapNode
{
T1 key;
T2 value;
//Ctor
mapNode(T1 t1, T2 t2): key(t1), value(t2)
{
}
//getters
const T1& first() const
{
return key;
}
const T2& second() const
{
return value;
}
//operators
bool operator==(const mapNode& rhs)const
{
return key == rhs.key;
}
bool operator<(const mapNode& rhs) const
{
return key < rhs.key;
}
mapNode& operator=(const mapNode& rhs)
{
key = rhs.key;
value = rhs.value;
}
};
//data
vector<mapNode> TheMap;
public:
void insert(const T1& k, const T2& v)
{
mapNode mn(k, v);
TheMap.push_back(mn);
}
int size() const
{
return TheMap.size();
}
const T1& getKeyAt(int i) const
{
return TheMap[i].first();
}
const T2& getValueAt(int i) const
{
return TheMap[i].second();
}
mapNode& find(const T1& key) const
{
//create the data type first needed for searching.
mapNode tmp(key, ); //This is the issue.
typename vector<mapNode>::const_iterator pos;
find(TheMap.begin(), TheMap.end(), key);
//if(pos != TheMap.end() )
//return *pos;
}
};
int main()
{
MyMap<int, string> m_MyMap;
m_MyMap.insert(1, "abc");
m_MyMap.insert(2, "def");
m_MyMap.insert(3, "ghi");
for(int i = 0; i < m_MyMap.size(); i++)
{
cout<<m_MyMap.getKeyAt(i)<<":"<<m_MyMap.getValueAt(i)<<endl;
}
m_MyMap.find(2);
return 0;
}