[c++] Remove from the beginning of std::vector

I have a vector of the following data structure

struct Rule {
        int m_id = -1;
        std::wstring name;
        double angle;
    };

std::vector<Rule>& topPriorityRules;

and I am erasing the first element of the vector using

topPriorityRules.erase(topPriorityRules.begin());

Is there any other good alternative for removing elements from the front of a std::vecor?

This question is related to c++ c++11

The answer is


Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.


Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;