2012-04-10 30 views
11

我不知道是否有辦法相交或使std::map<MyData*, MyValue>用標準算法(如std::set_intersect有沒有辦法相交/ diff一個std :: map和一個std :: set?

的問題是,我需要計算所述一組和之間的差定義爲std::set<MyData*>兩個結構和之間的差異但我想避免重新分配它(因爲它是每秒鐘處理大量數據結構的東西)。有沒有辦法獲得std::map的「關鍵視圖」?畢竟,我正在尋找的是在進行set操作時只考慮關鍵字,因此從實現的角度來看,它應該是可能的,但我一直無法找到任何東西。在有序的集合

#include <algorithm> 
#include <iostream> 
#include <map> 
#include <iterator> 
#include <string> 
#include <set> 
#include <vector> 

#include <boost/iterator/transform_iterator.hpp> 

typedef std::map<std::string, int> map_t; 
typedef std::set<std::string> set_t; 

const map_t::key_type & getKey(const map_t::value_type & pair) 
{ 
    return pair.first; 
} 

typedef const map_t::key_type & (*getKey_t)(const map_t::value_type &); 

typedef boost::transform_iterator<getKey_t, map_t::iterator> key_iterator_t; 

int main() 
{ 
    map_t map; 
    map["a"]=1; map["b"]=2; 
    set_t set; 
    set.insert("a"); set.insert("c"); 

    std::vector<std::string> v; 

    std::set_intersection(set.begin(), set.end(), 
     key_iterator_t(map.begin(), getKey), 
     key_iterator_t(map.end(), getKey), 
     std::back_inserter(v)); 
    std::copy(v.begin(), v.end(), 
     std::ostream_iterator<std::string>(std::cout," , ")); 
} 
+0

查看boost迭代器庫中的filter_iterator。 – 2012-04-10 14:37:12

+1

對不起,不是filter_iterator - transform_iterator。請參閱匿名的答案。 – 2012-04-10 14:50:26

回答

8

您可以爲了適應std::map迭代器,並只返回鍵使用transform_iterator的提升。你可以編寫一個自定義迭代器來封裝標準映射迭代器並返回鍵。然後你可以使用set_intersect

相關問題