1

I've spent a while researching this, and haven't found an answer yet, and I know that a 40+ year old language with all sorts of features probably does this.

I'm looking for a data structure to hold 500 ints only. I need to be able to compare the max int in that with a given int. I also want the structure to remove the earliest inserted, like a queue.

Is there a data structure that supports both? I do not need random access except to run min() on it.

There are priority queues, which support max but they don't autohandle the size. I can write my own function to do this but thought I would ask anyways/

JohnAllen
  • 7,317
  • 9
  • 41
  • 65

1 Answers1

1

To hold just 500 integers you want a circular buffer. It's in Boost:

http://www.boost.org/doc/libs/release/doc/html/circular_buffer.html

But this won't help you find the min or max in the container. For that you'll need these:

http://en.cppreference.com/w/cpp/algorithm/min_element http://en.cppreference.com/w/cpp/algorithm/max_element http://en.cppreference.com/w/cpp/algorithm/minmax_element

You can't exactly do both at once, because the requirement to remove the oldest element first requires sorting by insert order, whereas the requirement to find the min or max element requires sorting in order of values somehow (either linear, or as a heap like priority_queue does).

Finding the min/max of 500 integers should be extremely fast on modern machines. But if you object to the algorithmic complexity of a linear scan, you can try this:

  1. Store your elements in a set<int> which gives you *begin() and *rbegin() to get the min and max values.
  2. Store iterators into the set in a separate circular buffer. Set iterators are not invalidated by insert and erase of other iterators, so this is safe. When the circular buffer is full, erase the oldest iterator from the set, then erase it from the circular buffer.
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Yeah I had come across that in my search. Was trying to find a built-in solution seeing as how I'm new to C++ and there are so many libs! – JohnAllen Apr 29 '16 at 05:00
  • @JohnAllen: The STL has a bunch of containers but there are tons more in Boost and even more elsewhere (Intel TBB, BitMagic, etc.). I've updated my answer with a hybrid idea if you want optimal big-O performance. – John Zwinck Apr 29 '16 at 05:02
  • 1
    "You can't exactly do both at once" - sure you can, if you use a data structure that's a combination of two linked lists, maintained in both age order and sorted order simultaneously. Or perhaps a tree/heap and a list, for efficient insertion in sorted order. But I doubt that's in the standard library. – user253751 Apr 29 '16 at 05:05