map
map
is a SORTED Associative Container that contains key-value pairs with unique keys.
- Keys are sorted.
- Search, removal, and insertion operations have logarithmic complexity.
- Maps are usually implemented as red-black trees.
Declaration
map<int, int> mp;
Initialisation
map<int, int> m;
m[1] = 5; // [(1, 5)]
m[3] = 14; // [(1, 5); (3, 14)]
m[2] = 7; // [(1, 5); (2, 7); (3, 14)]
m[0] = -1; // [(0, -1); (1, 5); (2, 7); (3, 14)]
Printing map
for (const auto &it : m) {
cout << it.first << " " << it.second << endl;
}
for (auto el:mapName)
{
cout << mapName.first << ", " << mapName.second << endl;
}
map
Methods
Element access
at()
- in map
at()
doesn't really have any advantage so better use[]
for map
access specified element with bounds checking
only use at()
for accessing elements NOT FOR giving values like this mp.at("hey") = "hello";
as it will ERROR
terminate called after throwing an instance of 'std::out_of_range'
what(): map::at
operator[]
- use
[]
for assigning values
Lookup - binary_search()
Alternatives
- use
find()
for search element'sIndex No.
- use
contains()
for checking element present or not: ⇢⇢ ☠️ Don't usebinary_search()
☠️- returns
true
orfalse
~~from C++ 20
- returns
- use
count()
for checking element present or not: ⇢⇢ ☠️ Don't usebinary_search()
☠️- returns
1
or0
- returns
💣 binary_search()
from STL MUST not be used with set
, multiset
, map
, multimap
. 💣
binary_search()
becomesO(n)
when used withset
,multiset
,map
,multimap
,unordered_set
,unordered_multiset
,unordered_map
,unordered_multimap
.All the Associative Containers have
O(log n)
alternative ofbinary_search()
↠find()
forIndexNo.
of target search elementcontains()
for element present or not --true
orfalse
count()
for element present or not --1
or0
lower_bound()
⇢ container's ownlower_bound()
upper_bound()
⇢ container's ownupper_bound()
equal_range()
⇢ container's ownequal_range()
unordered_set
,unordered_multiset
,unordered_map
,unordered_multimap
don't havelower_bound()
,upper_bound()
Hence, binary_search()
must not be used with Associative Containers
https://discuss.codechef.com/t/set-find-vs-binary-search-help-needed-asap/23991/6
binary_search
has a logarithmic time complexity only forLegacyRandomAccessIterators
. This is the case ofstd::vector iterators
, for example. Sets/multisets are trees, so their iterators don’t allow random access. This makesbinary_search()
run in linear time, which is significantly slower for a large range. This is whystd::set
andstd::multiset
have a “find
” function, whilevector
doesn’t. They need their own binary search implementation to be able to run in logarithmic time.For instance, if your range spans over 1000 elements,
binary_search()
will want to look at the element at position 500 first. Vector iterators are more or less pointers, it’s easy to dobegin + 500
with pointer arithmetics. Since the elements are sorted, we can remove half of the range with a single comparison. That’s whybinary_search()
is very efficient, with logarithmic complexity.❎ BUT, In a set or multiset, nodes that are neighbors in the tree are not necessarily neighbors in memory. So,
binary_search()
would not even be able to know how many elements are in the range, end - begin is not supported. So the search starts at begin the iterator is incremented, until it reaches a value not lower than the one we are searching for. This is whybinary_search()
has poor performance with sets, and you should use thefind()
function provided by that particular container, that has a more suitable search strategy.
find()
Time Complexity is :~ O(log n)
count()
Time Complexity is :~ O(log n)
count()
returns1
if theset
ormap
contains the element and0
if it doesn't.
contains()
~~ C++ 20
Time Complexity is :~ O(log n)
contains()
returnstrue
if theset
ormap
contains the element andfalse
if it doesn't.
upper_bound()
lower_bound()
Modifiers
clear()
clears the contents
insert()
insert_or_assign
inserts an element or assigns to the current element if the key already exists
emplace()
constructs element in-place
emplace_hint()
constructs elements in-place using a hint
try_emplace()
inserts in-place if the key does not exist, does nothing if the key exists
erase()
erases elements
swap()
swaps the contents
extract()
extracts nodes from the container
merge()
splices nodes from another container
map
based Problems
// 💣💣💣💣TO TRY 💣💣💣💣
unordered_map<int,int> unmap;
for(int i=0 ; i<nums.size() ; i++){
unmap[nums[i]]++;
if(unmap[nums[i]] >= 2) return true;
}
return false;