Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting element to a sorted vector and keeping elements sorted

So I have a vector, and I want the elements to be sorted at all times. How should I go about inserting an element into that vector and keeping the elements sorted when I pop them out. I looked into std::lower_bound, however, that gave the opposite of what I wanted.

For example, this is what I want: When I pop all the elements in the vector it should be: 1 2 3 4 5. That means the vector has to store them as 5 4 3 2 1. If use lower bound, the vector stores them as 1 2 3 4 5, and it is popped as 5 4 3 2 1. Also, a compare functor is going to be passed in so that the lower_bound function uses the compare functor. Is there a way to take the opposite of a compare functor?

like image 919
OGH Avatar asked Feb 24 '13 03:02

OGH


People also ask

How do you keep a vector sorted?

An unsorted vector can be sorted by using the function std::sort() : std::vector<int> v; // add some code here to fill v with some elements std::sort(v. begin(), v.

How do you add an element to a vector in sorted order?

put the element a into the vector keeping the vector sorted. This is better be done in two stages: (1) find point of insertion, (2) insert element at tha point. I do not see any vectors in your code. And then the element that must be put in.

Is vector always sorted?

The vector doesn't have to be sorted until you need to look something up in it, so you can quickly build an unordered collection, inserting elements with vector::push_back instead of insert_into_vector, and then sort the vector all at once with std::sort(v. begin(), v.

Can we use sort function in vector?

Sorting a vector in C++ can be done by using std::sort(). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort() but maintains the relative order of equal elements.


1 Answers

To keep your vector sorted all the time, you should always insert new elements into proper position. As you want to pop elements in ascending order and vector provides only pop_back() method you should sort elements in descending order. so first you need to find proper position and then insert there:

typedef std::vector<int> ints;

void insert( ints &cont, int value ) {
    ints::iterator it = std::lower_bound( cont.begin(), cont.end(), value, std::greater<int>() ); // find proper position in descending order
    cont.insert( it, value ); // insert before iterator it
}
like image 185
Slava Avatar answered Sep 18 '22 16:09

Slava