Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy std::map to std::set in c++

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.

like image 767
linello Avatar asked Jun 06 '12 14:06

linello


1 Answers

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.

like image 64
betabandido Avatar answered Sep 27 '22 22:09

betabandido