使用提升复制将结构的成员作为键映射到设置容器中

copy member of struct as key map into set container using boost copy

本文关键字:映射 设置 成员 复制 结构      更新时间:2023-10-16

具有以下结构:

struct MixingParts{
int intPart;
double doublePart;
}

和 std::map 如下:

std::map<MixingParts, std::vector<int> > MixingMap;

我发现 boost::copy 非常有用,如果您请帮助我仅提取结构体的整数部分作为上述地图的键并将其插入回 std::set intSet,我将不胜感激;

boost::copy(MixingMap | boost::adoptors::map_keys(.....*Is it possible to use bind here?*...), std::inserter(intSet, intSet.begin())

我只能使用 C++98,并且赞赏任何其他不那么冗长和优化的解决方案。

boost::transform(mm, std::mem_fn(&MixingParts::intPart), 
    std::inserter(intSet, intSet.begin())));

或将copy/copy_rangetransformed适配器一起使用

下面是一个集成的实时示例:

住在科里鲁

#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <iostream>
struct MixingParts{
    int intPart;
    double doublePart;
};
using boost::adaptors::transformed;
int main() {
    std::vector<MixingParts> v { { 1,0.1 }, {2, 0.2}, {3,0.3} };
    boost::copy(v | transformed(std::mem_fn(&MixingParts::intPart)),
            std::ostream_iterator<int>(std::cout, " "));
}

指纹

1 2 3 

boost::mem_fn也可以使用。

for (MixingMap::const_iterator it = mm.begin(); it != mm.end(); ++it)
    intSet.insert(it->first.intPart);

在 C++11 中它会不那么冗长,但按照 C++98 的标准,它几乎没有臃肿。 而且它简单且效率最佳(考虑到数据结构的选择)。