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
?
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.
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.
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.
Three suggestions:
std::deque
instead of std::vector
for better performance in your specific case and use the method std::deque::pop_front()
.&
in std::vector<ScanRule>& topPriorityRules;
std::vector::erase()
(see Caleth's comment below).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With