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

Is it possible if the STL algorithm will deeply copy the std :: map values ​​to std :: set?

I do not want to explicitly embed in a new set.

I do not 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 finding a more consistent and elegant way to do this with a deep copy of the meanings.

+5
source share
1 answer

How 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 pointers. If you need a deep copy, you will 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 (available only with C ++ 11). If you cannot use C ++ 11, you can use a function object .

+8
source

All Articles