Search code examples
c++vectorshared-ptr

how to store and reference large amount of data in c++


I am using a vector of strings in order to store some data in memory. Database is not an option. More precisely an array of vector of strings. A simple scenario: I need to store the names of people living in 256 cities.

Example

NewYork: John, Bod, ...
London: Jim, Bill...

for this requirement I used

vector<std::string> city[256];

A new requirement came to create a new "class Person" that will hold more data per item

class person {
 string name;
 string surname;
 string email;
 int age;
};

I am addressing this issue in order to find the optimal way to store and shared those data.

vector<class person> city[256];

Obviously is better to use a pointer to objects. does shared_ptr applies here? We have TR1 installed in the system but we cannot use boost libs.


Solution

  • If you have C++11 and only need a single, global version of this data, you could use a data structure like this:

    #include <unordered_map>
    #include <unordered_set>
    #include <string>
    
    typedef std::unordered_multiset<std::string> name_set;
    typedef std::unordered_map<std::string, name_set> city_map;
    
    city_map city_db {
      { "Moscow", { "Ivan", "Igor", "Vladimir" } },
      { "Madrid", { "Julio", "Pedro", "Sanchez" } },
      { "Munich", { "Sepp", "Huber", "Maier" } }
    };
    
    int main()
    {
      return city_db["Munich"].size(); // just as an example
    }