1

Are there any ordered container that allow O(n) in-ordered deletion and traversal? I'm trying to do the following:

Hello  -> 1,2,3,4,5,6
Hello1 -> 24,15,13,10,8,7

I need to be able to insert and delete continuously from Hello or Hello1 as quickly as possible. I was thinking of using a priority queue, but each time I want to delete I spend O(logn) adjusting, so n deletions will cost me O(nlogn) time to keep the internal structure ordered. Are there any data structures that can accomplish this task in O(n) time?

Bob John
  • 3,504
  • 14
  • 35
  • 55
  • 1
    How about a `std::set`, or `std::multiset`? – Kerrek SB Mar 30 '13 at 19:34
  • http://stackoverflow.com/q/222658/1175253 – Sam Mar 30 '13 at 19:35
  • I should have mentioned that I also need to update values periodically. With a set or multiset this is more difficult to accomplish, as I understand. – Bob John Mar 30 '13 at 19:36
  • Can you clarify what 'but each time I want to delete I spend O(logn) adjusting, so n deletions will cost me O(nlogn) time to keep the internal structure ordered' exactly means? Do you want to delete a whole number of items all at once? – mikyra Mar 30 '13 at 19:39
  • The priority queues internal structure has to be maintained when a delete happens (to keep order), which takes O(logn) time. Thus, if I delete n separate elements from a priority queue I'll spend O(nlogn) doing it. – Bob John Mar 30 '13 at 19:41
  • @BobJohn when you modify values, are you identifying the value to modify by *index* or *value*? – Drew Dormann Mar 30 '13 at 19:43
  • You can `const_cast` to modify a set if you can guarentee the ordering is correct. – Alex Chamberlain Mar 30 '13 at 19:44
  • @DrewDormann by index. – Bob John Mar 30 '13 at 19:50

1 Answers1

0

Just use a std::vector, with some sorting pegged on top; don't use std::sort every time - use a merge sort.

Complexity is important, but when the data set is small the time taken for memory allocation and cache misses will far out way this. Generally, profile it, but I would conject in this case a vector will be fine.

Think carefully about if you need to keep the structure always sorted; can you insert a number of items before resorting? What about 2 vectors and merging on a lookup? Think carefully about your algorithms; you can delete any number of items in O(n), for instance.

Alex Chamberlain
  • 3,977
  • 2
  • 20
  • 48