Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove from the beginning of std::vector [closed]

Tags:

c++

c++11

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?

like image 923
sohel14_cse_ju Avatar asked Nov 17 '16 14:11

sohel14_cse_ju


People also ask

How do you remove an element from the beginning of a vector in C++?

To remove first element of a vector, you can use erase() function. Pass iterator to first element of the vector as argument to erase() function.

Can we pop from front in vector?

Implement pop_front operation for a vector in C++The pop_front operation should remove the first element from the vector and maintain the order of the remaining elements. We know that std::vector only supports push_back and pop_back operations. Both operations run in constant time.


2 Answers

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.

like image 157
eerorika Avatar answered Oct 19 '22 00:10

eerorika


Three 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;
  3. Use std::vector::erase() (see Caleth's comment below).
like image 22
VCSEL Avatar answered Oct 19 '22 00:10

VCSEL