There are two ways in which I can easily make a key,value attribution in C++ STL: maps and sets of pairs. For instance, I might have
map<key_class,value_class>
or
set<pair<key_class,value_class> >
In terms of algorithm complexity and coding style, what are the differences between these usages?
A pair is a single unit with two members. A map has keys and values in it. So you can use pairs to fill up a map, the elements of the pair becoming key and value.
The map solution results in "Time Limit Exceeded on Test 3", whereas the set solution results in "Time Limit Exceeded on Test 2", which means that Test 2 is such that the map solution works faster on it than the set solution.
at() over [] is the fact that it can operate on a const std::map , whereas [] won't.
The map and the multimap are both containers that manage key/value pairs as single components. The essential difference between the two is that in a map the keys must be unique, while a multimap permits duplicate keys.
They are semantically different. Consider:
#include <set> #include <map> #include <utility> #include <iostream> using namespace std; int main() { pair<int, int> p1(1, 1); pair<int, int> p2(1, 2); set< pair<int, int> > s; s.insert(p1); s.insert(p2); map<int, int> m; m.insert(p1); m.insert(p2); cout << "Set size = " << s.size() << endl; cout << "Map size = " << m.size() << endl; }
http://ideone.com/cZ8Vjr
Output:
Set size = 2
Map size = 1
Set elements cannot be modified while they are in the set. set
's iterator
and const_iterator
are equivalent. Therefore, with set<pair<key_class,value_class> >
, you cannot modify the value_class
in-place. You must remove the old value from the set and add the new value. However, if value_class
is a pointer, this doesn't prevent you from modifying the object it points to.
With map<key_class,value_class>
, you can modify the value_class
in-place, assuming you have a non-const reference to the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With