Here is a quick example to get to you started with boost::multi_index_container. Multi_index containers enables defining containers maintaining one or more indices with different sorting and access semantics.
Here is a sample program to get you started:
Here is a sample program to get you started:
#include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/hashed_index.hpp> #include <iostream> class CartItem{ public: int64_t cartItemId; int barcode; char symbol[10]; int64_t validityDate; float price; }; struct CartItemByCartItemIdIndexTag{}; struct CartItemByBarcodeIndexTag{}; typedef boost::multi_index_container< CartItem, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< boost::multi_index::tag<CartItemByCartItemIdIndexTag>, boost::multi_index::member<CartItem, int64_t, &CartItem::cartItemId> >, boost::multi_index::hashed_unique< boost::multi_index::tag<CartItemByBarcodeIndexTag>, boost::multi_index::member<CartItem, int, &CartItem::barcode> > > > CartItemMapContainer; typedef CartItemMapContainer::index<CartItemByCartItemIdIndexTag>::type CartItemByCartItemIdIndex; typedef CartItemMapContainer::index<CartItemByBarcodeIndexTag>::type CartItemByBarcodeIndex; //Global Variable CartItemMapContainer itemmultiIndexContainer; void insertItem(int64_t cartItemId, int barcode){ CartItem c; c.cartItemId = cartItemId; c.barcode = barcode; //Insert operation CartItemByCartItemIdIndex& index = itemmultiIndexContainer.get<CartItemByCartItemIdIndexTag>(); if(!index.insert(c).second){ std::cout << "Error inserting item"; } else std::cout << "Insert successful\n"; } void searchByItemId(int64_t cartItemId){ CartItem d; //Find Operation by CartItemId CartItemByCartItemIdIndex& idx = itemmultiIndexContainer.get<CartItemByCartItemIdIndexTag>(); CartItemByCartItemIdIndex::iterator itrb = idx.find(cartItemId); if(itrb == idx.end()){ std::cout << "Look up By CartItemId failed"; return; } else d = (*itrb); std::cout << "CartItemId:" << d.cartItemId << ", Barcode:" << d.barcode << std::endl; } void searchByBarcode(int barcode){ CartItem e; CartItemByBarcodeIndex& indexByBarCode = itemmultiIndexContainer.get<CartItemByBarcodeIndexTag>(); CartItemByBarcodeIndex::iterator itr = indexByBarCode.find(barcode); if(itr == indexByBarCode.end()){ std::cout << "look up By BarCode failed"; return; } else e = *itr; std::cout << "CartItemId:" << e.cartItemId << ", Barcode:" << e.barcode << std::endl; } int main(){ insertItem(1,2); insertItem(2,4); insertItem(3,6); searchByItemId(1); searchByBarcode(6); return 0; }
No comments:
Post a Comment