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
    • 存储方式待定

associative container 关联容器

  • 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

选择合适的容器

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,980评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,178评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,868评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,498评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,492评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,521评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,910评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,569评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,793评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,559评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,639评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,342评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,931评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,904评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,144评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,833评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,350评论 2 342

推荐阅读更多精彩内容

  • 7月17周一,开始我的减肥日程,第一天减肥,我给自己的目标是,跳绳30分钟,爬楼梯30分钟,可是跳绳那个说真的,真...
    冬影枕流阅读 226评论 0 0
  • 2017.6.29 跟自己做个约定 希望下一年的自己能够独立去做某件事情,有时候迈出一步你才会发现你自己之前的圈子...
    午间西瓜阅读 152评论 0 0
  • 今日关键词:【优秀】 上周四去HG法院开庭,正好赶上法官是该院的副院长。副院长亲力亲为审理本案,一下午2个多小时的...
    罗艺律师阅读 480评论 0 0