STL向量,迭代器和插入(C ++) [英] STL Vector, Iterator and Insert (C++)
问题描述
我有一个向量的迭代器传递的方法。
在这个方法中,我想添加一些元素到向量中,但是我不知道这是否可能,当只有迭代器
void GUIComponentText :: AddAttributes(vector< GUIComponentAttribute *> :: iterator begin,vector< GUIComponentAttribute *> :: iterator end)
{
for > :: iterator i = begin; i!= end; ++ i)
{
GUIComponentAttribute& attrib = *(* i)
//这里是分析的GUIComponentAttribute对象 - 如果出现
//特殊类型的对象,我想向向量中添加一些元素
}
}
< h2_lin>解决方案
首先,你必须改变界面。给定两个迭代器
,没有办法返回到它们引用的容器;所以如果
你想修改容器,你必须传递一个引用,
ie:
void GUIComponentText :: AddAttributes(
std :: vector< GUIComponentAttribute *>& attributes)
{
for(std :: vector< GUIComponentAttribute *> :: iter = attributes.begin();
iter!= attributes.end();
++ iter)
{
// ...
} $ b b}
完成后:插入可以使迭代器无效。所以它取决于
你想插入。如果你想在当前的
位置插入: std :: vector<> :: insert
单个元素返回一个
迭代器元素,这是插入你的元素之前,所以你
可以将它分配给你的迭代器,调整(如果必要),并继续:
code> iter = attributes.insert(iter,newAttribute);
++ iter; //返回我们的位置...
如果您要追加( push_back
),问题有点复杂;
你需要计算偏移量,然后重建迭代器:
size_t offset = iter - attributes.begin ;
attributes.push_back(nweAttribute);
iter = attributes.begin()+ offset;
在这种情况下,使用 size_t
和
[]
,而不是迭代器。
I have a method to which a vector's iterator is passed. In this method I'd like to add some elements into the vector, but I am not sure whether this is possible when having only the iterator
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
}
}
Thanks Markus
First, you'll have to change the interface. Given two iterators, there's no way to get back to the container to which they refer; so if you want to modify the container, you'll have to pass a reference to it, i.e.:
void GUIComponentText::AddAttributes(
std::vector<GUIComponentAttribute*>& attributes )
{
for ( std::vector<GUIComponentAttribute*>::iter = attributes.begin();
iter != attributes.end();
++ iter )
{
// ...
}
}
Having done that: insertion can invalidate iterators. So it depends on
where you want to insert. If you want to insert at the current
position: std::vector<>::insert
of a single element returns an
iterator to that element, which was inserted before your element, so you
can assign it to your iterator, adjust (if necessary), and continue:
iter = attributes.insert(iter, newAttribute);
++ iter; // Return to where we were...
If you're appending (push_back
), the problem is a bit more complex;
you need to calculate the offset, then reconstruct the iterator:
size_t offset = iter - attributes.begin();
attributes.push_back( nweAttribute );
iter = attributes.begin() + offset;
In this case, it is probably simpler to iterate using a size_t
and
[]
, rather than an iterator.
这篇关于STL向量,迭代器和插入(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!