brentf
brentf

Reputation: 411

Implementing unordered maps in C++

I need to create a simple lookup function for a program and want to confirm the best way to accomplish the task. I have a two-column CSV file that represents a string (key) and double (value) pair. The list is about 3,000 rows / key-value pairs. I will be doing about 5,000 lookups on this table each time my program is executed. Some psuedo-code is below followed by a few questions:

 CSV file - columns are "Tenant" and "PD"

 // Declare an unordered map
 unordered_map<string,double> TenantPDLookup;

 // Read from CSV file into the map object - I can do this part
 void ReadTenantLookup(unordered_map<string,double> TenantPDLookup) {...}

 // Lookup the values (PD) based on a series of keys (Tenant)
 // Here is my code that is not working (note this is a type string, string)
 string GetTenantRating(string const& TenantName, Assumptions& Ass, 
               tenant_lookup_map const& TenantRatingLookup) {

      auto TenantRating = TenantRatingLookup.find(TenantName);

      if (TenantRating == TenantRatingLookup.end())
           return Ass.DefaultTenantRating;
      return TenantRating->second;
 }

My questions about how to implement this are as follows:

  1. How do I do the actual lookup? I am thinking a simple function that returns the value when passed (a) a reference to my map and (b) a key. Can someone provide a simple framework
  2. My string values are "orderable" in the sense that they are alpha terms - should I somehow make this into an ordered list to facilitate faster lookups?
  3. Does this approach make sense?

Upvotes: 2

Views: 1000

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275878

// Declare an unordered map
typedef std::unordered_map<std::string,double> pd_lookup_map;
pd_lookup_map TenantPDLookup;

// Read from CSV file into the map object - I can do this part
pd_lookup_map ReadTenantLookup() {
  pd_lookup_map retval;
  // read std::string and double from file
  std::string key_from_file;
  double value_from_file;
  retval[key_from_file] = value_from_file;
  // repeat for entire file

  return retval; // is very efficient to return std containers by value
}

// Lookup the values (PD) based on a series of keys (Tenant)
// How do I do this part?
double GetTenantPD(unordered_map const& TenantPDLookup, std::string const& Key, double default_value = 0.0) {
  auto it = TenatePDLookup.find(Key);
  if (it == TenatePDLookup.end())
    return default;
  return *it;
}

This assumes you'd rather have a default value than expose an error if the Key is not found.

If you want to indicate that the key was not found, you'll have to do something different when it == blah.end() after a find( ).

Upvotes: 3

Related Questions