May 14, 2010

Example Using std::map<> In C++

See Wikipedia reference
std::map<XXX*, DataAveragerPtr> averagerCache;
const XXX* xxx = ...

DataAveragerPtr averager;
if(averagerCache.find(xxx) == averagerCache.end())
{ // Not found so create a new one
  averager.reset(new SomeDataAverager(...));     
  averager->DoSomethingExpensive();
  averagerCache.insert (std::pair<XXX*, DataAveragerPtr>(
  xxx, averager));
}
else // found it
{
  // for parametric types <A, B> use an A to get a B,
  // B b = mymap[a]; where a is of type A
  averager = averagerCache[xxx]; // lookup
}
...
if (!averagerCache.empty())
averagerCache.clear();
When passing it as a parameter, the best option is to pass it by reference and just create it on the stack.

No comments: