2016-05-06 13 views
0

私はboost :: multi_indexコンテナを持っています。誰かが特定のキーに基づいて一連のイテレータを取得する方法を教えてもらえますか?数時間の検索の後、私はlower_boundまたはupper_boundがトリックを行うべきであるという考えを持っていましたが、まだ例はありません。次の例では、22と24の間の価格ですべてのイテレータを取得したいと考えています。ありがとうございました。すべての一致を見つける方法キーを使ってboost :: multi_index?

struct order              
{                 
    unsigned int id;           
    unsigned int quantity;          
    double   price;           

    order(unsigned int id_, unsigned int quantity_, double price_) 
     :id(id_), quantity(quantity_), price(price_){} 
} 
typedef multi_index_container<          
    order,               
    indexed_by<              
    ordered_unique<            
     tag<id>, BOOST_MULTI_INDEX_MEMBER(order, unsigned int, id), 
     std::greater<unsigned int>>,         
    ordered_non_unique<           
     tag<price>,BOOST_MULTI_INDEX_MEMBER(order ,double, price)> 
    >                
> order_multi;                
int main()                
{                  
    order_multi order_book;           

    order_book.insert(order(/*id=*/0, /*quantity=*/10, /*price=*/20)); 
    order_book.insert(order(/*id=*/1, /*quantity=*/11, /*price=*/21)); 
    order_book.insert(order(/*id=*/3, /*quantity=*/12, /*price=*/22)); 
    order_book.insert(order(/*id=*/2, /*quantity=*/1, /*price=*/22)); 
    order_book.insert(order(/*id=*/4, /*quantity=*/1, /*price=*/23)); 
    order_book.insert(order(/*id=*/5, /*quantity=*/1, /*price=*/24)); 
    order_book.insert(order(/*id=*/6, /*quantity=*/1, /*price=*/24)); 
    order_book.insert(order(/*id=*/7, /*quantity=*/1, /*price=*/26)); 

    }                                 

答えて

1

は[lower_bound(22)upper_bound(24))、つまりあなたが後にしている範囲がされています。あなたが見つけた場合、それはあなたが使用する必要がlower_またはupper_boundだとき

auto first=order_book.get<price>().lower_bound(22); 
auto last=order_book.get<price>().upper_bound(24); 
for(;first!=last;++first)std::cout<<first->id<<" "; // prints 3 2 4 5 6 

それが混乱を決定するために、そこにありますあなたがC++ 11を使用して

auto range=order_book.get<price>().range(
    [](double p){return p>=22;}, // "left" condition 
    [](double p){return p<=24;}); // "right" condition 
for(;range.first!=range.second;++range.first)std::cout<<range.first->id<<" "; 

:おそらく正しい(とわずかに速い)を取得する方が簡単ですrange member functionラムダ関数を持つ。ネイティブのラムダ関数を使用せずにC++ 03でrangeを使用することもできますが、Boost.Lambdaに頼らざるを得ないか、rangeで受け入れられたファンクタを手書きで書く必要があります。どちらのオプションもおそらく面倒です。

+0

Cool。 'range()'メンバ関数についてはTILを参照してください。どうして私はそんなに長い間それを見逃すことができましたか?ところで、 'for(auto&el:boost :: make_iterator_range(order_book.get ().range(...))){...}'を使っています – sehe

関連する問題