Skip to content

Instantly share code, notes, and snippets.

@ahmedahamid
Last active May 10, 2016 02:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahmedahamid/c915de5f7d2287f34df6 to your computer and use it in GitHub Desktop.
Save ahmedahamid/c915de5f7d2287f34df6 to your computer and use it in GitHub Desktop.
Why I started to feel differently about C# | Using STL map
//
// (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