My vote goes to a function
But you see, if you want to do what manav wants to do (print the element corresponding to a key, as per the Python example), has_key() is a complete waste of time. You would just write something along these lines:
Code:
std::map<K,V>::iterator iter = map.find(key);
if (iter != map.end())
{
std::cout << iter->second << std::endl;
}
else
{
std::cout << "No such key: " << key << std::endl;
}
If you write:
Code:
if (map.has_key(key))
{
std::cout << map[key] << std::endl;
}
else
{
std::cout << "No such key: " << key << std::endl;
}
... you would be finding the key twice, assuming the key exists.
Of course! I would even like to extend the class std::map.
But some would advice against it, just like they did in case of mystring class example!
There is nothing wrong with extending std::map by providing free functions that extend its interface, or by wrapping it in another class. However, you should not inherit from std::map since it was not designed to be a base class and thus its destructor is non-virtual.
What is somekey here? Where do i get it from?
A working example would be:
Code:
template<typename K, typename V>
bool has_key(const std::map<K,V>& map, const K& key)
{
return map.find(key) != map.end();
}