Effective STL 23 Consider replacing associative container with sorted vector

If we choose an associative container, we’ll almost certainly be using a balanced binary tree. Such a tree would be made up of tree nodes. each holding not only a Widget, but also a pointer to the node’s left child, a pointer to its right child, and a pointer to its parent.
In contrast, there is no overhead when we store a Widget in a vector. The vector itself has overhead, of course, and there may be empty (reserved) space at the end of vector.

using a sorted vector instead of a set

vector<Widget> vw;

// lots of insertions, few lookups
... 

// multiset, stable_sort                
sort(vw.begin(), vw.end());     

// object for value to look up
Widget w;               
... 

// lookup via binary_search             
if (binary_search(vw.begin(), vw.end(), w)...

// lookup via lower_bound   
vector<Widget>::iterator i = lower_bound(vw.begin(), vw.end(). w);
if (i != vw.end() && !(w < *i))...

// lookup via equal_range
pair<vector<Widget>::iterator, vector<Widget>::iterator> 
    range = equal_range(vw.begin(), vw.end(), w);
if(range.fist != range.second)... 

// start Recorganize phase
...                         

using a sorted vector instead of a map

typedef pair<string, int> Data;

class DataCompare {
public:
    bool operator()(const Data& lhs, const Data& rhs) const {
    return keyLess(lhs.first, lhs.second);
    }
    bool operator()(const Data& lhs, const Data::first_type& k) const {
    return keyLess(lhs.first, k);
    }
    bool operator()(const Data::first_type& k, const Data& rhs) const {
    return keyLess(k, rhs.first);
    }
private:
    bool keyLess(const Data::first_type& k1, const Data::second_type& k2) const {
    return k1 < k2;
    }
};

vector<Data> vd;
...
sort(vd.begin(), vd.end(), DataCompare());

string s;
...
if (binary_search(vd,begin(), vd.end(), s, DataCompare())..

// lookup via lower_bound
// !DataCompare(lhs, k) 
// when it is true, we get i;
vector<Data>::iterator i = lower_bound(vd.begin(), vd.end(), s, DataCompare()); 
if (i != vd.end() && !DataCompare()(s, *i))...

// lookup via equal_range
pair<vector<Data>::iterator, vector<Data>::iterator> 
    range = equal_range(vb.begin(), vb.end(), s, DataCompare());
if (rang.first != rang.second) ...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值