GeekBand筆記: STL與泛型編程(容器)

stl

  • stl 6 components
    • allocator
    • container
    • algorithm
    • iterator
    • functor
    • adaptor

sequential container 順序容器

  • elements are stored and accessed sequentially by their position in the container

    • the sequence of elements is corresponding with the position while they adding to the container, not their value.
  • category of sequential container

    • vector
    • deque (double-ended queue)
    • list
    • forward_list (singly linked list)
    • array
    • string
  • sequential container adaptor 順序容器適配器

    • stack
    • queue
    • priority_queue
  • performance trade-offs(性能折中) of container

    • the costs to add/remove elements in container
    • the costs to random access the elements
  • contiguous-memory container (vector, string, array)

    • support fast random access
    • In exchange, add/remove element in the middle of container is inefficient
  • list storage container (list, forward_list)

    • fast to add/remove an element anywhere.
    • In exchange, not support random access
    • Moreover, memory overhead is often substantial. If your program has lots of small elements and space overhead matters, don’t use list or forward_list
  • deque
    • supports fast random access
    • fast insert/delete at front or back
    • 存儲(chǔ)方式待定

associative container 關(guān)聯(lián)容器

  • Elements in an associative container are stored and retrieved by a key

    • In contrast, elements in a sequential container are stored and accessed sequentially by their position in the container.
  • two primary types

    • map

      • The elements in a map are key–value pairs
      • use as dictionary
      • often refer to as an associative array. an associative array is like a normal array except that its subscript don't have to be int.
    • set

      • A set element contains only a key
      • a set is most useful when we simply want to know whether a value is present. for example: white-list
      • use when to keep elements sorted and unique
// elements ordered by key
map // key-value pairs, unique key
set // key is the value, unique key
multimap // allow multiple key
multiset

// unordered key
unordered_map
unordered_set
unordered_multimap
unordered_multiset
  • pair: key-value
    • the data members of pair are public. these members are named first and second
    • In a map, the elements are key-value pairs. That is each element is a pair object.
      • map<T1,T2>::value_type => pair<const T1, T2> //the value type of map is a pair and we can change the value but not the key of pair!
      • map<T1,T2>::key_type => T1
      • map<T1,T2>::mapped_type => T2
pair<T1, T2> p(v1, v2)
pair<T1, T2> p = {v1, v2}
make_pair(v1, v2)

p.first
p.second
  • set<T>::iterator are const

    • the keys in a set are const!, we can use a set iterator to read, but not write.
  • associative container and algorithm

    • In general, we do not use the generic algorithm with associative container. the fact that the keys are const means that we can not pass the associative container iterators to algorithm that write or reorder container elements.
    • associative container can be used with read-only algorithm. however, it is much faster to use the find member(map.find()) than to call generic version.
    • In practice, if we can use an associative container with the algorithm either as source sequence or as destination.
    set<int> c;
    vector<int> v;
    copy(c.begin(), c.end(), back_inserter(v, v.end())) // as a source sequence
    copy(v.begin(), v.end(), inserter(c, c.end())) // as a destination
    

container common operation

typedef in container

common

iterator
const_iterator
size_type
difference_type
value_type
reference
const_reference

associative container

key_type    // type of the key
mapped_type // type associated with each key, map only
value_type // for set, same as key_type; for map, pair<const key_type, mapped_type>

constructor and assignment

common

C c;
C c1(c2); // container type and element type must match
C c(b, e);  // when pass iterators. no requirement that container types are identical, Moreover element type can differ as long as compatible

C c{a,b,c...}; // list initialization.
C c={a,b,c...};

c1 = c2
c1 = {a,b,c...} // replace with the initializer list
a.swap(b) // swap is usually much faster than copy b to a
swap(a,b) //

only for seq container, not valid for associative containers or array

seq.assign(b, e)
seq.assign(il)
seq.assign(n,t)

size

c.size() // forward_list not support
c.max_size()
c.empty()

relational operator

the container type and element type of operands must be identical.

common
==, !=

all except unordered associative container
>, >=, <, <=

add/remove

common, but not support array

c.insert(args)
c.emplace(inits) //???

sequential container add

// add in front or back
c.push_back(t)
c.push_front(t) // only list and deque

// add in anywhere(before the element denoted by iterator p)
c.insert(p, t)  
c.insert(p, n, t)
c.insert(p, b, e) // return an iterator to the first element inserted
c.insert(p, il)

c.emplace_back(args) // args pass to element type's constructor
c.emplace_front(args)
c.emplace(p, args)

associative container add

c.insert(b, e) // iterator range
c.insert(il) // map.insert({word, 1})
.... TODO

remove

common

c.erase(args)
c.clear

sequential container remove

c.pop_back() // return void
c.pop_back()
c.erase(p)
c.erase(b, e) // return an iterator to the element after the last deleted one
c.clear() // return void

access element

sequential container access

c.back() // not for forward_list
c.front()

// ranom access: at() and subscript(operator[]) valid only for contiguous-memory containers
c[n] // no bounds checked, if overrun, undefined error happen. more efficient than at
c.at(n) // bounds checked, if overrun, throw out_of_range exception

notes:

  • make sure the container is not empty, or undefined error happen
  • all access operation return a reference.
  • safe random access
    • operator[] must be "in range [0, size)", or undefined happen.
      • it's up to the programmer to ensure that the index is valid
      • compiler will not check whether the index is out_of_range
    • use at() to ensure the index is invalid
      • if the index is invalid, throw an out_of_range exception

resize a container

c.resize(n) // if n<c.size(), the excess elements are discarded
c.resize(n, t)

capacity

c.shrink_to_fit()
c.capacity()
c.reserve(n)

container operation may invalidate iterator

  • container operations add, remove, or resize, may invalidate pointers, references, or iterators to container elements.
    • it's an serious run-time error to use an invalidated pointers, references, or iterators, as using uninitialized pointer
  • ensure pointers, references, or iterators is refreshed when container is changed by add/remove/resize

選擇合適的容器

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末朵夏,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子苦丁,更是在濱河造成了極大的恐慌遍尺,老刑警劉巖傅瞻,帶你破解...
    沈念sama閱讀 218,525評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)剿吻,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來串纺,“玉大人丽旅,你說我怎么就攤上這事》墓祝” “怎么了榄笙?”我有些...
    開封第一講書人閱讀 164,862評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)祷蝌。 經(jīng)常有香客問我茅撞,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,728評(píng)論 1 294
  • 正文 為了忘掉前任米丘,我火速辦了婚禮剑令,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘拄查。我一直安慰自己吁津,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評(píng)論 6 392
  • 文/花漫 我一把揭開白布堕扶。 她就那樣靜靜地躺著碍脏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪挣柬。 梳的紋絲不亂的頭發(fā)上潮酒,一...
    開封第一講書人閱讀 51,590評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音邪蛔,去河邊找鬼急黎。 笑死,一個(gè)胖子當(dāng)著我的面吹牛侧到,可吹牛的內(nèi)容都是我干的勃教。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼匠抗,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼故源!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起汞贸,我...
    開封第一講書人閱讀 39,244評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤绳军,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后矢腻,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體门驾,經(jīng)...
    沈念sama閱讀 45,693評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評(píng)論 3 336
  • 正文 我和宋清朗相戀三年多柑,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了奶是。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,001評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡竣灌,死狀恐怖聂沙,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情初嘹,我是刑警寧澤及汉,帶...
    沈念sama閱讀 35,723評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站削樊,受9級(jí)特大地震影響豁生,放射性物質(zhì)發(fā)生泄漏兔毒。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評(píng)論 3 330
  • 文/蒙蒙 一甸箱、第九天 我趴在偏房一處隱蔽的房頂上張望育叁。 院中可真熱鬧,春花似錦芍殖、人聲如沸豪嗽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽龟梦。三九已至,卻和暖如春窃躲,著一層夾襖步出監(jiān)牢的瞬間计贰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工蒂窒, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留躁倒,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,191評(píng)論 3 370
  • 正文 我出身青樓洒琢,卻偏偏與公主長(zhǎng)得像秧秉,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子衰抑,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評(píng)論 2 355

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

  • 7月17周一象迎,開始我的減肥日程,第一天減肥呛踊,我給自己的目標(biāo)是砾淌,跳繩30分鐘,爬樓梯30分鐘谭网,可是跳繩那個(gè)說真的拇舀,真...
    冬影枕流閱讀 230評(píng)論 0 0
  • 2017.6.29 跟自己做個(gè)約定 希望下一年的自己能夠獨(dú)立去做某件事情,有時(shí)候邁出一步你才會(huì)發(fā)現(xiàn)你自己之前的圈子...
    午間西瓜閱讀 156評(píng)論 0 0
  • 今日關(guān)鍵詞:【優(yōu)秀】 上周四去HG法院開庭蜻底,正好趕上法官是該院的副院長(zhǎng)。副院長(zhǎng)親力親為審理本案聘鳞,一下午2個(gè)多小時(shí)的...
    羅藝律師閱讀 483評(píng)論 0 0