项目作者: amallia

项目描述 :
Constant-Time Array Initialization
高级语言: C++
项目地址: git://github.com/amallia/InitializableArray.git
创建时间: 2018-07-22T18:17:05Z
项目社区:https://github.com/amallia/InitializableArray

开源协议:MIT License

下载


InitializableArray

Constant-Time Array Initialization

Build Status

Problem definition

Assume we have an array A[1, n] l-bit entries where only a small fraction of them will be written and then the array will be discarded, but we need to initialize all the cells of A. The effort to initialize A may then be too large compared to the little use we will make of it.

Solution

Use a second array D[1, n] and a stack S[1, s] (whose size is initially s = 0 and will become s = m). The following invariant will be maintained:

A[i] has been written <==> 1 <= D[i] <= s AND S[D[i]] = i

Usage

  1. #include <stdio>
  2. #include "InitializableArray.hpp"
  3. int main(int argc, char const *argv[]) {
  4. // Initialize
  5. arr:
  6. InitializableArray<int> array(100 /* size */, 0 /* default value */);
  7. // Iterate with for-range
  8. for (auto &&i : array) {
  9. std::cout << i << std::endl; // It prints 0
  10. }
  11. array.set(10 /* position */, 1 /* value */);
  12. std::cout << array[10] << std::endl; // It prints 10
  13. array.clear(10); // Clear position 10
  14. std::cout << array[10] << std::endl; // It prints 0 again
  15. // Iterate with for loop
  16. for (size_t i = 0; i < array.size(); ++i) {
  17. array.set(i, i); // It sets the position as value
  18. }
  19. array.clear(); // Clear all array
  20. for (auto &&i : array) {
  21. std::cout << i << std::endl; // It prints 0 again
  22. }
  23. return 0;
  24. }