6

是否可以使用 STL 算法将 std::map 值深度复制到 std::set?

我不想明确插入新集合。

不想明确地这样做:

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);
}

但要找到一种更简洁、更优雅的方式来做到这一点,并具有深刻的价值副本。

4

1 回答 1

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.

于 2012-06-06T16:07:06.530 回答