I'm trying to store two different values with the same key in an unordered_map. To do so I used a vector to hold the values. I want to recall a previously store value if the index is specified when I call with store->get() or else it returns just the latest value. When I run my test code, it always returns the first value store in the vector. When I debug I do see a second value stored in the vector at set(). But when the times come to get(), the vector only contain the first element. How can that be?
using namespace std;
int main() {
class store
{
std::unordered_map<string, std::vector<string>> container;
public:
int set(string key, string value)
{
//find if the key exist
if (container.find(key) != container.end())
{
//if yes insert at last position and return last index
auto vec = container[key];
vec.push_back(value);
return vec.size() - 1;
}
//if not insert in vector and return index 0
else
{
std::vector<string> tmpVec;
tmpVec.push_back(value);
container[key] = tmpVec;
return 0;
}
};
string get(string key, int timestamp = -1)
{
if (container.find(key) != container.end())
{
auto vec = container[key];
if (timestamp >= 0)
{
return vec[timestamp];
}
else
{
return vec[vec.size() - 1];
}
}
return "";
};
};
store* store1 = new store();
auto timestamp1 = store1->set("foo", "bar");
store1->set("foo", "hello");
cout << "value at timestamp1: " << store1->get("foo", timestamp1) << endl;;
cout << "last value:" << store1->get("foo") << endl; //expected hello
return 0;
}