LinkedHashMap

linked_hash_map.h

#ifndef LINKED_HASH_MAP_H_
#define LINKED_HASH_MAP_H_
#include <unordered_map>
#include <list>
#include "basic_macro.h"
#include "logging.h"
// This holds a list of pair<Key, Value> items.  This list is what gets
// traversed, and it's iterators from this list that we return from
// begin/end/find.
//
// We also keep a map<Key, list::iterator> for find.  Since std::list is a
// doubly-linked list, the iterators should remain stable.
template <class Key, class Value, class Hash = std::hash<Key>>
class linked_hash_map
{
  private:
    typedef std::list<std::pair<Key, Value>> ListType;
    typedef std::unordered_map<Key, typename ListType::iterator, Hash> MapType;

  public:
    typedef typename ListType::iterator iterator;
    typedef typename ListType::reverse_iterator reverse_iterator;
    typedef typename ListType::const_iterator const_iterator;
    typedef typename ListType::const_reverse_iterator const_reverse_iterator;
    typedef typename MapType::key_type key_type;
    typedef typename ListType::value_type value_type;
    typedef typename ListType::size_type size_type;

    linked_hash_map() = default;
    explicit linked_hash_map(size_type bucket_count) : map_(bucket_count) {}

    linked_hash_map(linked_hash_map &&other) = default;
    linked_hash_map &operator=(linked_hash_map &&other) = default;

    // Returns an iterator to the first (insertion-ordered) element.  Like a map,
    // this can be dereferenced to a pair<Key, Value>.
    iterator begin()
    {
        return list_.begin();
    }
    const_iterator begin() const
    {
        return list_.begin();
    }

    // Returns an iterator beyond the last element.
    iterator end()
    {
        return list_.end();
    }
    const_iterator end() const
    {
        return list_.end();
    }

    // Returns an iterator to the last (insertion-ordered) element.  Like a map,
    // this can be dereferenced to a pair<Key, Value>.
    reverse_iterator rbegin()
    {
        return list_.rbegin();
    }
    const_reverse_iterator rbegin() const
    {
        return list_.rbegin();
    }

    // Returns an iterator beyond the first element.
    reverse_iterator rend()
    {
        return list_.rend();
    }
    const_reverse_iterator rend() const
    {
        return list_.rend();
    }

    // Front and back accessors common to many stl containers.

    // Returns the earliest-inserted element
    const value_type &front() const
    {
        return list_.front();
    }

    // Returns the earliest-inserted element.
    value_type &front()
    {
        return list_.front();
    }

    // Returns the most-recently-inserted element.
    const value_type &back() const
    {
        return list_.back();
    }

    // Returns the most-recently-inserted element.
    value_type &back()
    {
        return list_.back();
    }

    // Clears the map of all values.
    void clear()
    {
        map_.clear();
        list_.clear();
    }

    // Returns true iff the map is empty.
    bool empty() const
    {
        return list_.empty();
    }

    // Removes the first element from the list.
    void pop_front() { erase(begin()); }

    // Erases values with the provided key.  Returns the number of elements
    // erased.  In this implementation, this will be 0 or 1.
    size_type erase(const Key &key)
    {
        typename MapType::iterator found = map_.find(key);
        if (found == map_.end())
            return 0;

        list_.erase(found->second);
        map_.erase(found);

        return 1;
    }

    // Erases the item that 'position' points to. Returns an iterator that points
    // to the item that comes immediately after the deleted item in the list, or
    // end().
    // If the provided iterator is invalid or there is inconsistency between the
    // map and list, a CHECK() error will occur.
    iterator erase(iterator position)
    {
        typename MapType::iterator found = map_.find(position->first);
        if(found->second != position){
            DLOG(FATAL)<<"Inconsisent iterator for map and list, or the iterator is invalid.";
        }

        map_.erase(found);
        return list_.erase(position);
    }

    // Erases all the items in the range [first, last).  Returns an iterator that
    // points to the item that comes immediately after the last deleted item in
    // the list, or end().
    iterator erase(iterator first, iterator last)
    {
        while (first != last && first != end())
        {
            first = erase(first);
        }
        return first;
    }

    // Finds the element with the given key.  Returns an iterator to the
    // value found, or to end() if the value was not found.  Like a map, this
    // iterator points to a pair<Key, Value>.
    iterator find(const Key &key)
    {
        typename MapType::iterator found = map_.find(key);
        if (found == map_.end())
        {
            return end();
        }
        return found->second;
    }

    const_iterator find(const Key &key) const
    {
        typename MapType::const_iterator found = map_.find(key);
        if (found == map_.end())
        {
            return end();
        }
        return found->second;
    }

    // Returns the bounds of a range that includes all the elements in the
    // container with a key that compares equal to x.
    std::pair<iterator, iterator> equal_range(const key_type &key)
    {
        std::pair<typename MapType::iterator, typename MapType::iterator> eq_range =
            map_.equal_range(key);

        return std::make_pair(eq_range.first->second, eq_range.second->second);
    }

    std::pair<const_iterator, const_iterator> equal_range(
        const key_type &key) const
    {
        std::pair<typename MapType::const_iterator,
                  typename MapType::const_iterator>
            eq_range =
                map_.equal_range(key);
        const const_iterator &start_iter = eq_range.first != map_.end() ? eq_range.first->second : end();
        const const_iterator &end_iter = eq_range.second != map_.end() ? eq_range.second->second : end();

        return std::make_pair(start_iter, end_iter);
    }

    // Returns the value mapped to key, or an inserted iterator to that position
    // in the map.
    Value &operator[](const key_type &key)
    {
        return (*((this->insert(std::make_pair(key, Value()))).first)).second;
    }

    // Inserts an element into the map
    std::pair<iterator, bool> insert(const std::pair<Key, Value> &pair)
    {
        // First make sure the map doesn't have a key with this value.  If it does,
        // return a pair with an iterator to it, and false indicating that we
        // didn't insert anything.
        typename MapType::iterator found = map_.find(pair.first);
        if (found != map_.end())
            return std::make_pair(found->second, false);

        // Otherwise, insert into the list first.
        list_.push_back(pair);

        // Obtain an iterator to the newly added element.  We do -- instead of -
        // since list::iterator doesn't implement operator-().
        typename ListType::iterator last = list_.end();
        --last;

        map_.insert(std::make_pair(pair.first, last));

        return std::make_pair(last, true);
    }

    size_type size() const
    {
        return list_.size();
    }

    template <typename... Args>
    std::pair<iterator, bool> emplace(Args &&... args)
    {
        ListType node_donor;
        auto node_pos =
            node_donor.emplace(node_donor.end(), std::forward<Args>(args)...);
        const auto &k = node_pos->first;
        auto ins = map_.insert({k, node_pos});
        if (!ins.second)
            return {ins.first->second, false};
        list_.splice(list_.end(), node_donor, node_pos);
        return {ins.first->second, true};
    }

    void swap(linked_hash_map &other)
    {
        map_.swap(other.map_);
        list_.swap(other.list_);
    }

  private:
    // The map component, used for speedy lookups
    MapType map_;

    // The list component, used for maintaining insertion order
    ListType list_;

    // |map_| contains iterators to |list_|, therefore a default copy constructor
    // or copy assignment operator would result in an inconsistent state.
    DISALLOW_COPY_AND_ASSIGN(linked_hash_map);
};
#endif

[1] 圖解LinkedHashMap原理

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末橘券,一起剝皮案震驚了整個濱河市辟宗,隨后出現(xiàn)的幾起案子膛堤,更是在濱河造成了極大的恐慌仍秤,老刑警劉巖罢坝,帶你破解...
    沈念sama閱讀 216,843評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異唉铜,居然都是意外死亡筷屡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評論 3 392
  • 文/潘曉璐 我一進(jìn)店門尚骄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來块差,“玉大人,你說我怎么就攤上這事倔丈『┤颍” “怎么了?”我有些...
    開封第一講書人閱讀 163,187評論 0 353
  • 文/不壞的土叔 我叫張陵需五,是天一觀的道長鹉动。 經(jīng)常有香客問我,道長宏邮,這世上最難降的妖魔是什么泽示? 我笑而不...
    開封第一講書人閱讀 58,264評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮蜜氨,結(jié)果婚禮上械筛,老公的妹妹穿的比我還像新娘。我一直安慰自己飒炎,他們只是感情好埋哟,可當(dāng)我...
    茶點故事閱讀 67,289評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著郎汪,像睡著了一般赤赊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上怒竿,一...
    開封第一講書人閱讀 51,231評論 1 299
  • 那天砍鸠,我揣著相機與錄音,去河邊找鬼耕驰。 笑死爷辱,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播饭弓,決...
    沈念sama閱讀 40,116評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼双饥,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了弟断?” 一聲冷哼從身側(cè)響起咏花,我...
    開封第一講書人閱讀 38,945評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎阀趴,沒想到半個月后昏翰,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,367評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡刘急,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,581評論 2 333
  • 正文 我和宋清朗相戀三年棚菊,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片叔汁。...
    茶點故事閱讀 39,754評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡统求,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出据块,到底是詐尸還是另有隱情码邻,我是刑警寧澤,帶...
    沈念sama閱讀 35,458評論 5 344
  • 正文 年R本政府宣布另假,位于F島的核電站像屋,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏浪谴。R本人自食惡果不足惜开睡,卻給世界環(huán)境...
    茶點故事閱讀 41,068評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望苟耻。 院中可真熱鬧篇恒,春花似錦、人聲如沸凶杖。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽智蝠。三九已至腾么,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間杈湾,已是汗流浹背解虱。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留漆撞,地道東北人殴泰。 一個月前我還...
    沈念sama閱讀 47,797評論 2 369
  • 正文 我出身青樓于宙,卻偏偏與公主長得像,于是被迫代替她去往敵國和親悍汛。 傳聞我的和親對象是個殘疾皇子捞魁,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,654評論 2 354

推薦閱讀更多精彩內(nèi)容