As in the title I am trying to write a template class map that is build on vector of structs where I hold the key that is a string and a value of template TYPE. There is the short main program that represents the usage of my class:
int main()
{
map<int> iv;
iv["john"] = 23;
int ia = iv["john"]++;
int ib = iv["john"];
cout << ia << " " << ib << endl; // prints 23 24
try{
int ic = iv["jack"]; // should throw an exception
}catch(map<int>::Uninitialized&)
{
cout << "Uninitialized map element!" << endl;
};
}
And there is the class i have managed to write:
class map
{
private:
struct FIELD
{
string key;
TYPE value;
};
vector<FIELD> data;
public:
TYPE& operator[] (const string index)
{
typename vector<FIELD>::iterator idx;
for(idx = data.begin(); idx != data.end(); ++idx)
{
if(idx->key == index) return idx->value;
}
if(idx == data.end())
{
FIELD toAdd;
toAdd.key = index;
data.push_back(toAdd);
}
for(idx = data.begin(); idx != data.end(); ++idx)
{
if(idx->key == index) return idx->value;
}
return idx->value;
}
};
It only works properly for assignment operations like `iv["john"] = 23; but when I try to read elements that are not initialized the operator[] creates new element that only contains the key and this is wrong. I know there is no such thing like checking if the value is uninitialized. The problem is that both writing and reading operation call operator[] and I don't quite understand how to throw an exception in this situation. I have looked all over the web and found that I can create two indexing operators, one for reading and one for writing - like this:
TYPE& operator[] (const string index)
TYPE operator[] (const stirng index) const;
and the compiler will know when to use which. But I guess it will not solve the problem at all.