Re: I cannot use the hash_map::operator to read the value in the hash map?
On Aug 2, 7:25 am, tony_in_da...@yahoo.co.uk wrote:
On Aug 2, 1:47 pm, xz <zhang.xi...@gmail.com> wrote:
like km1.put(2, 40); in Java
like int a = (int) hm1.get(2); in Java
I think hash map is so basic data structure, why is it such a headache
to use this famous HASH MAP?
In java, life is simple......
This is simple? This is hideous compared to the natural operator
Still, the STL version is worse:
std::map< X, int >::const_iterator it = hm1.find( key ) ;
int a = it == hm1.end() ? 42 : *hm1 ;
The real problem in reading a map (or a hashmap) is how to
handle missing values. Sometimes, an exception is appropriate,
but it's not a good general solution. So you need something out
And should I include <hash_map> or <hash_map.h> ?
I thought it should be
but turns out:
error: hash_map: No such file or directory
Whatever the documentation for your system tells you. The
latest draft says <unordered_set>, but this is fairly recent,
and it's likely that your implementation still uses something
pre-standard. Which it *should* document.
If you want to be a programmer, you should at least know how to do a
recursive directory search for filenames including *hash*. Really,
kids these days.... ;-P
Given that the correct name is unordered_set, searching for a
file whose name includes *hash* isn't going to help. More
generally, of course, recursive directory search is almost
certainly the wrong way to go about it here.
FWIW, many people just use std::map, which has a similar interface,
the benefit of sorting the elements, is standardised and portable
(just #include <map>), and is unlikely to have a noticeable
performance difference unless you're inserting tens of thousands or
more elements for frequent lookup or the elements are difficult to
compare. Basically, map does a binary lookup which typically requires
approximately log2(N) element comparisons, or 10 for a thousand
elements, 20 for a million....
The advantage of std::map is that it has been in the standard
from the very beginning, and so is standard. The various
pre-standard implementations of hash_map varied somewhat, which
created no end of portability problems. In the near future, of
course, there's std::unordered_map. But I don't think you can
count on it yet.
Note too that std::map guarantees O(n ln n). unordered_set will
be *typically* O(n), but only if you have a good hashing
function on the key. And good hashing functions are not
necessarily trivial to come by.
James Kanze (GABI Software) email:email@example.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34