简体   繁体   中英

C++ insert an element to a vector

I am trying to build a priority queue using a vector that stores each element. Firstly, I wanna insert the element to the vector with its priority. I am not sure if it is possible, if not, Can someone give me another solution. Here is my code:

template <typename E>
class PriorityQueue {
private:
    std::vector<E> elements;
    E value;
    int pr; 

public:
  PriorityQueue() {}

  void insert(int priority, E element) {


  }   
};

The standard algorithm (see Introduction To Algorithms chapter 6) for doing this is as follows:

  1. When pushing an item, insert it to the end of the vector, then "bubble" it up to the correct place.

  2. When popping the smallest item, replace the first item (at position 0) with the the item at the end, then "bubble" it down to the correct place.

It's possible to show that this can be done with (amortized) logarithmic time (the amortization is due to the vector possibly doubling itself).

However, there is no need to implement this yourself, as the standard library contains std::priority_queue which is a container adapter using std::vector as its default sequence container. For example, if you define

std::priority_queue<int> q;

then q will be a priority queue adapting a vector.

Here is how to create an element with priority for vector:

 struct PriElement
    {
        int data;
        int pri;
        bool operator < ( const PriElement & other ) const
        {
            return pri < other.pri;
        }
    };

    vector<PriElement> _vector;

However, the real problem is to keep the vector sorted per priority.

Here is a naive implementation showing the bubble up method:

class PriorityQueue{

public:
    void insert( int data, int pri )
    {
        _vector.push_back(PriElement(data,pri));
        int index = _vector.size() -1;
        while ( ( index > 0 )&& (_vector[index] < _vector[index-1] ) )
        {
            swap(_vector[index],_vector[index-1]);
            index--;
        }

    }
private:

    vector<PriElement> _vector;
};

For any real world implementation, as mentioned, use priority_queue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM