C ++ is there a default data class for sorted indexes in an accessible manner at a reasonable rate?

I'm looking for a dataclass that keeps its data in order, but also allows it to be accessed in any order I want.

Basically I'm looking for a queue that allows me to access the elements in random order and also stay in order (lowest to highest). When adding items, it shouldn't use everything (O (n * log (n))), but instead just insert and delete it in a quick way (O (log (n))). I know there are data structures like this (binary tree queue), but does C ++ offer a suggestion? My current applications are asking if I can do things like get the middle from a queue / list of items, or get the second highest priority item. Does C ++ have a default data class for this? Or should I do it myself?

By the way, this is C ++ 98

+3


source to share


3 answers


I think vector plus heap is similar to what you are looking for.

vector<int> v;

// insert elements
v.push_back(3);
push_heap(v.begin(), v.end());

v.push_back(2);
push_heap(v.begin(), v.end());

v.push_back(4);
push_heap(v.begin(), v.end());

// get the second big
sort_heap(v.begin(), v.end());
cout << v[v.size() - 2] << endl;

// insert elements
make_heap(v.begin(), v.end());
v.push_back(7);
push_heap(v.begin(), v.end());

// get the second big
sort_heap(v.begin(), v.end());
cout << v[v.size() - 2] << endl;

      



The insertion is fast. But every time, before you want to access an element that is not the largest, you need to sort the heap, since the heap gives you the biggest. And after that and before the new insert you need to call make_heap

to make a bunch of vector again.

+1


source


You have to do it yourself.



Create a wrapper around std :: vector. Add the necessary methods to delegate the vector, for the insert methods, call std :: upper_bound to find where to insert.

0


source


No, such a structure does not exist in the standard library. I don't think it exists in boost, but looking at Boost.MultiIndex it doesn't hurt.

Otherwise, such a structure is conceptually simple: some kind of balanced search tree (possibly ab or red-black) that additionally needs to maintain the number of child nodes in it (which probably makes an ab tree with higher a and b more suitable, than 2-3 or red and black, but nothing seems to help you implement it.

0


source







All Articles