What are practical uses for STL's 'partial_sum'?

前端 未结 11 1699
耶瑟儿~
耶瑟儿~ 2021-02-04 03:47

What/where are the practical uses of the partial_sum algorithm in STL?

What are some other interesting/non-trivial examples or use-cases?

11条回答
  •  [愿得一人]
    2021-02-04 04:35

    I used it to reduce memory usage of a simple mark-sweep garbage collector in my toy lambda calculus interpreter.

    The GC pool is an array of objects of identical size. The goal is to eliminate objects that aren't linked to other objects, and condense the remaining objects into the beginning of the array. Since the objects are moved in memory, each link needs to be updated. This necessitates an object remapping table.

    partial_sum allows the table to be stored in compressed format (as little as one bit per object) until the sweep is complete and memory has been freed. Since the objects are small, this significantly reduces memory use.

    1. Recursively mark used objects and populate the Boolean array.
    2. Use remove_if to condense the marked objects to the beginning of the pool.
    3. Use partial_sum over the Boolean values to generate a table of pointers/indexes into the new pool.
      • This works because the Nth marked object has N preceding 1's in the array and acquires pool index N.
    4. Sweep over the pool again and replace each link using the remap table.

    It's especially friendly to the data cache to put the remap table in the just-freed, thus still hot, memory.

提交回复
热议问题