Deletion Method In C++


he following methods are available for deleting objects in the container classes vector, deque, and list: pop_back() deletes the last object in the container erase() deletes the object at a given position, or deletes all the objects in a given range clear() deletes all the objects in a container. The following method is additionally defined in the deque and list classes: pop_front() deletes the first object in the container. The method does not have a return value, just like the pop_back() method. The pop_back() and pop_front() methods are preferable on account of their constant runtimes. Using the erase() method to delete an object at the beginning or in the middle of a container also provides a constant runtime in the container class list. However, the runtime is linear in the vector and deque classes, since objects must be shifted within the container to fill the gap left by the deletion.

#include <queue> #include <string> #include <iostream> using namespace std; class Parcel { private: unsigned int prio; // Priority string info; public: Parcel(unsigned int p, const string& s) :prio(p), info(s) {} // Access methods, ... overloaded operators: friend bool operator<(const Parcel& x,const Parcel& y) { return (x.prio < y.prio); } friend ostream& operator<<(ostream& os, const Parcel& x) { os << x.prio << " "<< x.info << endl; return os; } }; int main() { priority_queue<Parcel> pq; pq.push(Parcel(7,"Bob")); // Insert pq.push(Parcel(1,"Peter")); pq.push(Parcel(4,"Susan")); while( !pq.empty() ) { cout << pq.top() << endl; // Output pq.pop(); // and delete } return 0; }