Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <map>
- #include <unordered_map>
- #include <iostream>
- struct CityRecord
- {
- std::string Name;
- uint64_t Population;
- double Latitude, Longitude;
- };
- namespace std
- {
- template<>
- struct hash<CityRecord>
- {
- size_t operator()(const CityRecord& key)
- {
- // Have to construct and then call it, syntax is weird
- // Cherno doesn't remember it, just ends up copy/pasting it from somewhere else
- return hash<std::string>()(key.Name);
- }
- };
- }
- int main()
- {
- //std::unordered_map<CityRecord, uint32_t> foundedMap;
- //foundedMap[CityRecord{ "Melbourne", 5000000, 2.4, 9.4 }] = 1850;
- // Index operator [ will always insert things in, no const version of this operator
- // If thing being inserted doesn't exist, it creates it and inserts it into unordered map and gives ref to new CityRecord
- //uint32_t melBourneFounded = foundedMap[CityRecord{ "Melbourne", 3487382, 2.4, 9.4 }];
- std::unordered_map<std::string, CityRecord> cityMap;
- cityMap["Melbourne"] = CityRecord{ "Melbourne", 5000000, 2.4, 9.4 };
- cityMap["Lol-town"] = CityRecord{ "Lol-town", 5000000, 2.4, 9.4 };
- cityMap["Paris"] = CityRecord{ "Paris", 5000000, 2.4, 9.4 };
- //cityMap["Berlin"] = CityRecord{ "Berlin", 5000000, 2.4, 9.4 };
- cityMap["London"] = CityRecord{ "London", 5000000, 2.4, 9.4 };
- // If you want to retrieve data without inserting it, use .at()
- const auto& cities = cityMap;
- //const CityRecord& berlinData = cities.at("Berlin");
- // How to check if data at .at is there
- if (cities.find("Berlin") != cities.end())
- {
- const CityRecord& berlinData4 = cities.at("Berlin");
- }
- // Below example but in C++14 AKA Stone Age
- //for (auto& kv : cityMap)
- //{
- // const std::string& name = kv.first;
- // CityRecord& city = kv.second;
- //}
- // Iterate through entire data structure
- // [ ] is structured bindings from C++17
- for (auto& [name, city] : cityMap)
- {
- std::cout << name << "\n Population: " << city.Population << std::endl;
- }
- std::cin.get();
- // More efficient vs one below, doesn't copy as it creates it in place and references the memory
- //CityRecord& berlinData2 = cityMap["Berlin"];
- //berlinData2.Name = "Berlin";
- //berlinData2.Population = 5;
- // Ends up copying from last line, not preferred to one above
- //CityRecord berlinData3;
- //berlinData3.Name = "Berlin";
- //berlinData3.Population = 5;
- //cityMap["Berlin"] = berlinData3;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement