2012-09-07 18 views
0

我已經將它歸結爲我能想到的最簡單的示例代碼。使用boost ::元組引用作爲ordered_unique索引的關鍵字來提升多索引插入錯誤

我有一個升壓多由成員索引:

typedef const boost::tuple<const uint32_t &, const uint8_t &> key_type; 

這樣做似乎使多指標認爲每一個項目是相等的(大小決不會> 1)

我存儲結構與2名成員,我想多索引的一個獨特的鑰匙是這兩個成員。我認爲製作一個引用元組可以簡單地完成這個任務。它並沒有像我預期的那樣行事。看起來,元組中的項目是引用每個新項目與現有項目衝突。也許值得注意的是,簡單地遠離引用會使代碼的行爲像我期望的那樣,但是這並不能幫助我理解爲什麼參考案例不起作用。

#include <stdint.h> 
#include <iostream> 
#include <boost/multi_index_container.hpp> 
#include <boost/multi_index/ordered_index.hpp> 
#include <boost/multi_index/sequenced_index.hpp> 
#include <boost/multi_index/member.hpp> 
#include <boost/multi_index/tag.hpp> 
#include "boost/tuple/tuple.hpp" 
#include "boost/tuple/tuple_comparison.hpp" 

namespace bmi = ::boost::multi_index; 

class MyMultiIndex { 
public: 
    MyMultiIndex() {} 
    ~MyMultiIndex() {} 

    // Switching away from references fixes everything.... 
    typedef const boost::tuple<const uint32_t &, const uint8_t &> key_type; 
    //typedef const boost::tuple<const uint32_t, const uint8_t> key_type; 

    struct Item { 
     const uint8_t thing1; 
     const uint32_t thing2; 
     key_type key; 

     Item(const uint8_t &a1, const uint32_t &a2) 
       : thing1(a1), thing2(a2), key(thing2, thing1) 
     {} 
    }; 

    struct key_idx {}; 

    typedef bmi::multi_index_container< 
     Item, 
     bmi::indexed_by< 
      bmi::ordered_unique<bmi::tag<key_idx>, 
           bmi::member<Item, key_type, &Item::key> 
      > 
     > 
    > imsi_map_type; 

    typedef imsi_map_type::index<key_idx>::type key_idx_type; 

    void insert(const uint8_t &a1, const uint32_t &a2) 
    { 
     Item item(a1, a2); 

     key_idx_type &idx(mi.get<key_idx>()); 
     std::pair<key_idx_type::iterator, bool> ret = idx.insert(item); 

     if (!ret.second) { 
      std::cout << "itr = " << (int)ret.first->thing1 << " " << ret.first->thing2 << std::endl; 
     } 
    } 
private: 
    imsi_map_type mi; 
}; 

int 
main() 
{ 
    MyMultiIndex mindex; 

    mindex.insert(1, 10); 
    mindex.insert(1, 20); 
    mindex.insert(3, 10); 

    return 0; 
} 

正如在示例中所述,如果我使元組保留值,而不是引用每個作品,因爲我期待。

我花時間尋找到各種可能性(晃來晃去引用,比較刺激:在一個較小的程序,沒有多指標參考元組等)

這裏是我的編譯命令: G ++ -O0 -ggdb -Wall -Werror test.cc -lboost_system -lpthread

運行程序給出:

ITR = 1 10 ITR = 1 10

顯示的是,即使我試圖插入1,20和3,10,多似乎認爲他們等於1,10。

我很困惑。任何和所有的幫助表示讚賞。

+0

沒有人關心,如果[「標題說明一切」](http://meta.stackexchange.com/q/145019/163768)。打開此頁面的人不一定需要拼湊你的意思。只需寫一個獨立,清晰的身體。 –

+0

Thans你,這是一個好點。我已經改變了當前的問題(希望更好),並將在發佈未來問題時記住這一點。 – user442585

+0

非常感謝! –

回答

2

Item的拷貝語義,如其缺省拷貝ctor所實現的,是有缺陷的。提供這樣的副本:

Item(const Item& x) 
    : thing1(x.thing1), thing2(x.thing2), key(thing2, thing1) 
{} 
+0

如果你想解決最初的問題,Boost.MultiIndex提供了組合鍵,而不需要使用你正在試驗的元組構造類型:http://www.boost.org/libs/multi_index/doc /tutorial/key_extraction.html#composite_keys –

+0

對我而言,多索引作者對SO的貢獻是多麼幸運:) – user442585

相關問題