C++ 从 std::vector 的开头删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40656871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove from the beginning of std::vector
提问by sohel14_cse_ju
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
?
从 a 的前面删除元素还有其他好的选择std::vecor
吗?
回答by eerorika
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
.
不需要重载迭代器来擦除 的第一个元素std::vector
。
P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.
如果您打算从前面擦除,PS Vector(动态数组)可能是错误的数据结构选择。
回答by VCSEL
Two suggestions:
两个建议:
- Use
std::deque
instead ofstd::vector
for better performance in your specific case and use the methodstd::deque::pop_front()
. - Rethink (I mean: delete) the
&
instd::vector<ScanRule>& topPriorityRules;
- 在您的特定情况下使用
std::deque
而不是std::vector
为了更好的性能并使用方法std::deque::pop_front()
。 - 反思(我的意思是:删除)
&
中std::vector<ScanRule>& topPriorityRules;