我有一个 vector 的迭代器传递给的方法。
在这种方法中,我想向 vector 中添加一些元素,但是我不确定只有迭代器时这是否可行
void GUIComponentText::AddAttributes(vector<GUIComponentAttribute*>::iterator begin, vector<GUIComponentAttribute*>::iterator end)
{
for (vector<GUIComponentAttribute*>::iterator i = begin; i != end; ++i)
{
GUIComponentAttribute &attrib = *(*i);
// Here are the GUIComponentAttribute objects analyzed - if an object of a
// special kind appears, I would like to add some elements to the vector
}
}
谢谢
马库斯
最佳答案
首先,您必须更改界面。给定两个迭代器,
无法返回他们所引用的容器;因此,如果
您想要修改容器,则必须传递对其的引用,
即:
void GUIComponentText::AddAttributes(
std::vector<GUIComponentAttribute*>& attributes )
{
for ( std::vector<GUIComponentAttribute*>::iter = attributes.begin();
iter != attributes.end();
++ iter )
{
// ...
}
}
完成此操作:插入会使迭代器无效。所以这取决于
您要插入的位置。如果要在当前位置插入
位置:单个元素的
std::vector<>::insert
返回一个该元素的迭代器,该元素插入在您的元素之前,因此您
可以将其分配给迭代器,进行调整(如有必要),然后继续:
iter = attributes.insert(iter, newAttribute);
++ iter; // Return to where we were...
如果要附加(
push_back
),则问题会更加复杂;您需要计算偏移量,然后重构迭代器:
size_t offset = iter - attributes.begin();
attributes.push_back( nweAttribute );
iter = attributes.begin() + offset;
在这种情况下,使用
size_t
和[]
,而不是迭代器。