I would use a multimap<Key,List<Item>::Iterator>
paired with a List<Item>
. I would use the map for lookup and the List would hold the items in insertion order. You will need to keep both containers up to date on all insertion/update/deletion scenarios. If you could expound on your use case a better option may be available.
This option would give you log(n) lookup while still allow constant time removal of the index and the item. This is similar to how I have implemented LRU caches in the past.
Edit due to question
typedef list<myData> DataLst;
typedef DataLst::iterator LstIter;
typedef multimap<unsigned long, LstIter> mpType;
mpType BuildIndex(DataLst &lst)
{
mpType ret;
for (auto Item = begin(lst); Item != end(lst); Item++)
{
ret.insert(make_pair(Item->id,Item));
}
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
DataLst myDataContainer;
myDataContainer.push_back(myData(1002, 1));
myDataContainer.push_back(myData(1001, 2));
myDataContainer.push_back(myData(1005, 3));
myDataContainer.push_back(myData(1003, 4));
myDataContainer.push_back(myData(1000, 5));
auto myMap = BuildIndex(myDataContainer);
auto iter = myMap.find(1001);
cout << "The iter insert = " << iter->second->insertionOrder << endl;
cout << "The iter insert after = " << std::next(iter->second)->insertionOrder << endl;
cout << "The iter insert before = " << std::prev(iter->second)->insertionOrder << endl;
string foo;
cin >> foo;
}
output
The iter insert = 2
The iter insert after = 3
The iter insert before = 1