Containers (map) Flashcards
How can you insert a new element in a map, and how do you know if the operation was succesful?
auto [It, success] = m_map.insert({23, "Value"}); cout << "Operation " << (success ? "Success" : "Failed") << "\n";
It
is the position where the elemet was inserted.
how do you know if a element was inserted into a map, using a Position as a reference?
auto Iti = m_map.insert(it, {23, "Value"}); cout << "Operation " << (it != m_map.end() ? "Success" : "Failed") << "\n";
On a map<K,V>
, What is the difference beteween operator[]
and insert
operator[]
create a new element (empty) if the key doesnt exist menwhile insert
doesn´t perform the operation.
The sintaxys of operator[]
is: T& = operator[cosnt Key&]
The sintaxys of insert
is: [iterator, bool] = insert( const value_type& value )
Over a map, whai is the difference between insert
and insert_or_assign
insert
doesn’t replace the value if the key is already inserted but insert_or_assign
does it.
Both of them return a pair with the iterator and operation result:std::pair<iterator, bool>
Which method do you use to find the firt elemetn that is greater than key?
Iterator upper_bound(const Key& key)
This operation can be considereted as:
Find the firt element that It > key
Complexity: O(log n)
Which method do you use to find the firt elemetn that is not less than key?
iterator lower_bound(const Key& key)
This operation can be considereted as:
Find the firt element that It >= key
Complexity: O(log n)
How do equal_range(x)
work?
having a collection of elements, with their respective keys, equal_range
will find the range where the key x is locates in the range [Rb, Re).
**This description asume that x is located in the map, but if not, the range will be something like:
a) for x < begin(): range will be [Rb, Rb)
b) for x >= end(): range will be [Re,)
For example:
```cpp
map<int, string> m_map {{1,”1”}, {2,”2”}, {3,”3”} ,{4,”4”} ,{5,”5”} ,{6,”6”} ,{7,”7”}}
auto rng = m_map.equal_range(x);
~~~
For x=4, the range will be: [4,5) wich means 4 >= 4 && 4 < 5
For x=-2, the range will be: [1,1) wich means -2 >= 1 && -2 < 1