Is there something like Haskell Data.Sequence in C ++?

Does the library use C++something like a container Haskell Data.Sequence?

I'm most interested in:

  • Preservation of the order of elements (in which they were inserted).
  • O(logn)index access. Aka operator[](size_type pos).
  • O(logn) insert / delete in the middle (by index).
+6
source share
1 answer

It seems to me that to implement such a data structure you will need a tree that stores the number of elements in each node. It allows you to insert and retrieve in O (log (N)), and indexes are supported simply by counting the number of elements in the “left” given node in the tree.

* , , , , SO.

A node :

template<typename T>
struct Node {
  Node* left;
  Node* right;
  size_t elements;
  T value

  T& access(size_t index) {
    if (left->elements == index) {
      return value;
    } else if (left->elements > index) {
      return left->access(index);
    } else {
      return right->access(index - left->elements - 1);
    }
  }

  void insert(size_t index, T&& value) {
    // insert `value` at right place, increment `elements`
  }
}

( insert .)

. , . , B- -.


:

- , , , std::vector. - O (N), O (log (N)), O (N) . :

  • .

  • ( , ), , .

  • , . , , , , , .

2 3 , . .

, . , , . std::vector<std::unique_ptr<T>>.

:

+3

All Articles