在C ++中将std :: map复制到std :: set [英] Copy std::map to std::set in c++

查看:434
本文介绍了在C ++中将std :: map复制到std :: set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible with a STL algorithm to deep copy a std::map values to a std::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.

推荐答案

怎么办?

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,该代码使用lambda函数(仅在C ++ 11中可用)。如果您不能使用C ++ 11,则可以使用功能对象

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

这篇关于在C ++中将std :: map复制到std :: set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆