Unordered_multimap :: bucket () return value when key does not exist?

If the key does not exist, then what unordered_multimap::bucket(key) should be returned?

The link says that it should return the bucket number for the bucket containing the key, but says nothing about what to expect if this key does not exist in unordered_multimap.

I tried this myself , but I got the wrong result:

 std::unordered_multimap<std::string, std::string> m = {{"jack", "foo"}, {"jill", "bar"}}; std::cout << "jack is in bucket " << m.bucket("jack") << std::endl; std::cout << "jill is in bucket " << m.bucket("jill") << std::endl; std::cout << "bjarne is in bucket " << m.bucket("bjarne") << std::endl; 

Output:

 jack is in bucket 3 jill is in bucket 4 bjarne is in bucket 4 

Does this mean that I should use say unordered_multimap::count(key) == 0 to catch non-existent keys?

+4
source share
2 answers

It returns the index of the bucket to which the key belongs, regardless of whether the key is inserted or not.

From the Standard (C ++ 11, ยง23.2.5, Table 103, p. 752):

b.bucket(k)

Returns the bucket index in which elements with keys equivalent to k will be found if such an element existed.

The only precondition is b.bucket_count > 0 (which is almost always the case). Theoretically, the default constructor unordered_multimap allowed to generate an initial hash with zero buckets, but I doubt that any implementation actually does this).


To check if a key exists (i.e. inserted), use

 b.count(key) > 0 

as you said or

 b.find(key) != b.end() 

(I would suggest that the latter tends to be more efficient, because checking for existence is, generally speaking, less effort than counting. This would be especially true in unordered_multimap .)

+4
source

Table of Tables 103 of the standard bucket return: "the bucket index in which elements with keys equivalent to k would be found if any such element existed." Therefore, if "bjarne" was in the multi-media, then it will be in bucket 4.

Sounds like you should use

unordered_multimap::count(key) == 0 or

unordered_multimap::find(k) == unordered_multimap::end() to check for nonexistent keys.

+1
source

Source: https://habr.com/ru/post/1488397/


All Articles