簡體   English   中英

使用boost copy將struct的成員作為鍵映射復制到set容器中

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

結構如下:

struct MixingParts{
int intPart;
double doublePart;
}

和std :: map如下:

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

我發現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())

我只能使用C ++ 98,任何其他不太冗長和優化的解決方案也值得贊賞。

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

或將copy / copy_rangetransformed適配器一起使用

這是一個集成的實時示例:

生活在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, " "));
}

打印

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標准中它幾乎不會hard腫。 而且它簡單且具有最佳的效率(根據數據結構的選擇)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM