2012-01-05 114 views
3

給出std :: map的兩個實例我試圖使用std :: set_set_symmetric_difference()算法來存儲所有差異。我有以下工作代碼:使用std :: set_symmetric_difference時在std :: map上使用STL容器的模板類型

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

typedef std::map<std::string,bool> MyMap; 
typedef std::vector< std::pair<MyMap::key_type,MyMap::mapped_type> > MyPairs; 

//typedef std::vector<MyMap::value_type> MyPairs; 

using namespace std; 
int main(int argc, char *argv[]) { 
    MyMap previous; 
    MyMap current; 

    //Modified value 
    previous["diff"] = true; 
    current["diff"] = false; 

    //Missing key in current 
    previous["notInCurrent"] = true; 

    //Missing key in previous 
    current["notInPrevious"] = true; 

    //Same value 
    previous["same"] = true; 
    current["same"] = true; 

    cout << "All differences " << endl; 
    MyPairs differences; 
    std::back_insert_iterator<MyPairs> back_it(differences); 
std::set_symmetric_difference(previous.begin(),previous.end(),current.begin(),current.end(),back_it); 

    for(MyPairs::iterator it = differences.begin(); it != differences.end(); it++){ 
     cout << "(" << it->first << ":" << it->second << ") "; 
    } 
    cout << endl; 

    return 0; 
} 

這將打印我的期望:

All differences 
(diff:0) (diff:1) (notInCurrent:1) (notInPrevious:1) 

我有什麼錯誤的類型定義爲MyPairs,從地圖不同的載體。

最初我試圖等作爲typedef std::vector<MyMap::value_type> MyPairs我降落了與在的Non-static const member, can't use default assignment operator

SetDifferenceMapVectorType.cpp:36: instantiated from here 
/usr/include/c++/4.2.1/bits/stl_pair.h:69: error: non-static const member 'const std::basic_string<char, std::char_traits<char>, std::allocator<char> > std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool>::first', can't use default assignment operator 

接受的答案中描述的下列誤差的typedef載體這是因爲在地圖的值的鍵是常量以避免更改密鑰並使地圖失效,這是合理的。因爲std::map<Key,Value>::value_typestd::pair<const Key, Value>含義operator=()不能用於添加元素到向量,這就是爲什麼不指定const作品在我的工作示例。

有沒有更好的方法來定義MyPairs向量的模板參數是不是多餘的?到目前爲止我所能得到的最好的結果是std::vector< std::pair<MyMap::key_type, MyMap::mapped_type> >

+0

這是一個更大的問題的一部分?如果是這樣,可能有一個解決方案,我們可以提供幫助 - 但就目前來看,我不認爲有任何方法可以更通用地添加大量代碼。 – Zac 2012-01-05 19:34:14

回答

2

我不確定這是不是您正在尋找的 - 它是一個元函數,用於從第一對類型中刪除const,以及返回新的配對類型。除非你想深入瞭解remove_const的工作方式 - 其他人將不得不提供幫助,否則需要提升。

#include <boost/type_traits/remove_const.hpp> 

template< typename PairType > 
struct remove_const_from_pair 
{ 
    typedef std::pair 
    < 
     typename boost::remove_const< typename PairType::first_type>::type, 
     typename PairType::second_type 
    > type; 
}; 

typedef std::map<std::string,bool> MyMap; 
//typedef std::vector< std::pair<MyMap::key_type,MyMap::mapped_type> > MyPairs; 

typedef std::vector< remove_const_from_pair<MyMap::value_type>::type > MyPairs; 
+0

不僅是提升可接受,它是非常鼓勵。我將現有代碼分解爲上面的示例,刪除現有的boost,並嘗試使boost :: remove_const工作。我認爲你釘住了我的失敗。謝謝! – Joel 2012-01-05 20:05:33

相關問題