-
-
Save kgashok/135a9f0b6e6e21126a11c0b139d4ddb6 to your computer and use it in GitHub Desktop.
Why I started to feel differently about C# | Using STL map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// (1) C++: - Defining a dictionary [key type=string, value type=int] | |
// - No easy way to initialize. | |
// | |
map<string, int> dict; | |
// | |
// (1`) C++11: Defining and initializing a dictionary [key type=string, value type=int] | |
// | |
map<string, int> dict | |
{ | |
{"Eve", 101}, | |
{"George", 150}, | |
{"Emma", 200} | |
}; | |
// | |
// (2) C++: Searching for any key (string) - an O(log(n)) operation | |
// | |
if (dict.find("James") != dict.end()) | |
// | |
// (3) C++: Search for any value (int) - a linear operation | |
// | |
typedef map<string, int>::const_iterator const_dict_iter; | |
for (const_dict_iter iter = dict.cbegin(); iter != dict.cend(); ++iter) | |
{ | |
if (iter->second == 120) | |
} | |
// | |
// (3`) C++11: Search for any value (int) - a linear operation - using C++11's auto + range-based for loop | |
// | |
for (const auto& pair : dict) | |
{ | |
if (pair.second == 120) | |
} | |
// | |
// (3``) C++11: Search for any value (int) - a linear operation - using C++11's lambdas | |
// | |
typedef map<string, int>::value_type dict_pair_type; | |
const auto iter = find_if(begin(dict), end(dict), [](const dict_pair_type& pair){ return pair.second == 120;}); | |
if (iter != end(dict)) | |
// | |
// (4, 5, 6) C++: Iterating over keys/values/pairs of a dictionary | |
// | |
typedef map<string, int>::const_iterator const_dict_iterator; | |
for (const_dict_iter iter = dict.cbegin(); iter != dict.cend(); ++iter) | |
{ | |
cout << iter->first; | |
cout << iter->second; | |
} | |
// | |
// (4`, 5`, 6`) C++11: Iterating over keys/values/pairs of a dictionary - using C++11's auto + range-based for loop | |
// | |
for (const auto& pair : dict) | |
{ | |
cout << pair.first; | |
cout << pair.second; | |
} | |
// | |
// (4``, 5``, 6``) C++11: Iterating over keys/values/pairs of a dictionary - using for_each + C++11's lambdas | |
// | |
typedef map<string, int>::value_type dict_pair_type; | |
for_each(begin(dict), end(dict), [](const dict_pair_type& pair){ cout << pair.first; cout << pair.second; }); | |
// | |
// (7) C++: Adding a key with a corresponding value | |
// | |
dict["Janice"] = 300; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment