6

Is it possible with a STL algorithm to deep copy a std::map values to a std::set?

I don't want to explicitly insert in the new set.

I don't want to explicitly do this:

std::map<int, double*> myMap; //filled with something
std::set<double*> mySet;

for (std::map<int, double*>::iterator iter = myMap.begin(); iter!=myMap.end(); ++iter)
{
     mySet.insert(iter->second);
}

but find a more coincise and elegant way to do this, with a deep copy of values.

linello
  • 8,451
  • 18
  • 63
  • 109
  • Add some code. Are you trying to copy the `map`'s `key_type` or the `value_type`? – dirkgently Jun 06 '12 at 14:54
  • 1
    What if there are duplicates? Should you be using a `multiset` instead? – Oliver Charlesworth Jun 06 '12 at 15:02
  • There will be no duplicates, and if there are, is not important. – linello Jun 06 '12 at 15:04
  • 1
    You could use the `select2nd` from SGI's STL, or from [a previous answer](http://stackoverflow.com/a/5218792/179910). – Jerry Coffin Jun 06 '12 at 16:19
  • Or, use a transform iterator that extracts the map key or value. I provided several implementations of a key iterator in [an answer to another question](http://stackoverflow.com/a/5099345/151292). Converting any of those to a value iterator would be a trivial task. When you say that you want a "deep copy," what you should really do is wrap your pointer in a handle class that performs the "deep" copy when it is copied. – James McNellis Jun 06 '12 at 22:53

1 Answers1

8

What about this?

std::transform(myMap.begin(), myMap.end(), std::inserter(mySet, mySet.begin()),
    [](const std::pair<int, double*>& key_value) {
        return key_value.second;
    });

This only copies the pointers, though. If you want a deep-copy, then you would need to do:

std::transform(myMap.begin(), myMap.end(), std::inserter(mySet, mySet.begin()),
    [](const std::pair<int, double*>& key_value) {
        return new double(*key_value.second);
    });

BTW, the code uses lambda functions (only available from C++11). If you cannot use C++11, you could use a function object, though.

betabandido
  • 18,946
  • 11
  • 62
  • 76