Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between set<pair> and map in C++?

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?

like image 426
Luís Guilherme Avatar asked Jul 14 '10 16:07

Luís Guilherme


People also ask

What is the difference between pair and map?

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.

Which is faster set or map?

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.

What is the difference between map () and map [] in STL?

at() over [] is the fact that it can operate on a const std::map , whereas [] won't.

What is the difference between map and multimap associative?

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.


2 Answers

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

like image 126
Philipp Avatar answered Sep 20 '22 11:09

Philipp


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.

like image 31
bk1e Avatar answered Sep 23 '22 11:09

bk1e