文章

lec4 Associative containers

none

Associative containers

Container Adaptors

Associative Containers

  • map/set: keys in sorted order, faster to iterate through a range of elements
    • it’s object seems like need and only need less operator(<)
  • unordered map/set: faster to access individual elements by key
  • stl does not follow all the theory: overload all the operators
  • use bool or integer to check whether the key is exit has no difference in performance
  • use braket seems will initial the no exit key-value, get will throw a exception

  • std::map<T>
  • mymap.at[key] vs. mymap[key]
  • Equivalent of Stanford .containsKey(key):
    • mymap.count(key)
    • And a (slightly faster) alternative that we’ll learn next lec
  • std::set<T>
  • A set is just a specific case of a map that doesn’t have a value!
    • or you can think of the value as being true(if present) or false
  • Literally all the same functions are the c++ map, minus element access(except .get())

Iterators

  • iterators allow iteration over any container, whether it is ordered or not
  • iterators let us view a non-linear collection in a linear manner
    • we can get an iterator pointing to the ‘start’ of the sequence by calling mySet.begin()
    • we can get the value of an iterator by using the dereference * operator
    • we can advance the iterator one by using the ++ operator(prefix)
    • we can check if we have hit the end by comparing to mySet.end()
  • for squential containers, iterators really are pointers under the hood(difference containers is different)
  • why ++ in the left instead of right?
    • 前置++(如 ++iter)的操作是直接在原迭代器上进行加1操作,并返回更新后的迭代器。这种方式更高效,因为它不需要额外的拷贝操作来保存原始值。在大多数情况下,特别是当迭代器只是用来遍历容器时,前置++是首选,因为它可以避免不必要的开销。而后置++(如 iter++)则会在执行加1操作之前先返回迭代器的一个副本,这个副本是加1操作之前的原始值。这意味着后置++涉及到一次额外的临时对象创建和返回,因此在性能上相对较低效。这种形式主要用在需要先使用当前值再递增的场景中,尽管这种情况在迭代器遍历中并不常见。
  • Summary
    • create iterator
    • Dereference iterator to read value currently pointed to
    • Advance iterator
    • Compare aginst another iterator(.end())
  • why is powerful?
    • Many scenarios require looking at elements, regardless of what type of container is storing those elements
    • iterator let us go through sequences of elements in a standardised way
本文由作者按照 CC BY 4.0 进行授权

热门标签