简体   繁体   English

使用boost copy将struct的成员作为键映射复制到set容器中

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

Having struct below: 结构如下:

struct MixingParts{
int intPart;
double doublePart;
}

and std::map as follow: 和std :: map如下:

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

I found boost::copy very useful, I will appreciate if you please help me to only extract integer part of struct as key of the above map and insert it back to the std::set intSet; 我发现boost :: copy非常有用,如果您能帮助我仅将struct的整数部分作为上述映射的键并将其插入回std :: set intSet;中,我将不胜感激。

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

I can only use C++98, and also any other solution which is less verbose and optimized is appreciated. 我只能使用C ++ 98,任何其他不太冗长和优化的解决方案也值得赞赏。

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

Or use copy / copy_range with transformed adaptor 或将copy / copy_rangetransformed适配器一起使用

Here's an integrated live example: 这是一个集成的实时示例:

Live On Coliru 生活在Coliru

#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, " "));
}

Prints 打印

1 2 3 

boost::mem_fn can be used too. boost::mem_fn也可以使用。

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

It would be less verbose in C++11, but it's hardly bloated by C++98 standards. 在C ++ 11中它不会那么冗长,但是在C ++ 98标准中它几乎不会hard肿。 And it's simple and optimally efficient (given the choice of data structures). 而且它简单且具有最佳的效率(根据数据结构的选择)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM