The following code shows a very basic but essential functionality I would like to create and am getting some nasty run-time errors currently which I have not been able to debug myself. I have been working to write a solution to what I am looking for and this is the closest I have come. Any help in identifying a fix or re-design of this implementation is greatly appreciated!
This is the class. What I am looking for is a map which can still perform its operator[key] functionality but also be iterated through in sequential order as the elements were added. I am attempting to do this by having a map for lookup with its value being a pointer to the real value being held in a vector of corresponding pairs.
template <typename t>
class IndexedMap {
public:
t& operator [] (string s) {
bool nu = true;
for (auto& e : actual) // for each pair
if (e.first == s) // if exist
nu = false;
if (nu == true) { // if needs created
actual.push_back(pair <string, t>()); // create proper pair
actual.back().first = s; // assign key
// create copy in map @ same key pointing to actual value
lookup[s] = &actual.back().second;
}
return *lookup[s]; // return reference to value
}
typename vector <pair <string, t>>::iterator begin () {
return actual.begin();
}
typename vector <pair <string, t>>::iterator end () {
return actual.end();
}
private:
vector <pair <string, t>> actual;
map <string, t*> lookup;
};
This implementation "works" with the following test.cpp- meaning that it will run and I actually do see the result I am looking for, but upon exit of test.cpp I am getting some crazy errors involving a call to free() and I am not sure how that is taking place or how to fix.
test.cpp :
int main () {
IndexedMap <vector <int>> test;
test["BILLS"]; test["GAS"];
test["GROCERY"]; test["PETS"];
test["TAKEOUT"]; test["OTHER"];
int i = 0;
for (auto e : test) // check order
cout << e.first << endl;
for (auto& e : test) // assign 3 unique values to each vector
for (int f = 0; f < 3; ++f, ++i)
e.second.push_back(i);
for (auto e : test) { // display them
cout << e.first << ":" << endl;
for (auto f : e.second)
cout << f << endl;
}
vector <int> blank; // test modifying a value
test["GAS"] = blank;
for (auto e : test["GAS"])
cout << e << endl;
cout << "hopefully empty?" << endl;
}
I hope this is not all too confusing the way I have explained or written this out. Many thanks in advance to any help that can be provided.
Happy new year everyone!