GeekBand笔记: STL与泛型编程(容器)

2016-04-14  本文已影响0人  Royye

stl

sequential container 顺序容器

associative container 关联容器

// 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<T1, T2> p(v1, v2)
pair<T1, T2> p = {v1, v2}
make_pair(v1, v2)

p.first
p.second

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:

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

选择合适的容器

上一篇 下一篇

猜你喜欢

热点阅读