gpt4 book ai didi

c++ - ptr_vector 迭代器不需要增量吗?

转载 作者:搜寻专家 更新时间:2023-10-31 01:21:16 25 4
gpt4 key购买 nike

#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
using namespace std;

class Derived
{
public:
int i;
Derived() {cout<<"Constructed Derived"<<endl;}
Derived(int ii):i(ii) {cout<<"Constructed Derived"<<i<<endl;}
~Derived() {cout<<"* Destructed Derived"<<i<<endl;}
};

int main()
{
boost::ptr_vector<Derived> pv;
for(int i=0;i<10;++i) pv.push_back(new Derived(i));

boost::ptr_vector<Derived>::iterator it;
for (it=pv.begin(); it<pv.end();/*no iterator increment*/ )
pv.erase(it);
cout<<"Done erasing..."<<endl;
}

请注意,第二个 for 循环不会递增迭代器,但它会迭代并删除所有元素。我的问题是:

  1. Is my technique of iteration and using the iterator correct?
  2. If iterator increment is not required in the for loop, then where does the increment happen?
  3. Is it better to use an iterator or will an ordinary integer suffice (ie: is there any value-add with using iterators)? (coz I can also erase the 5th element like pv.erase(pv.begin()+5);)
  4. Is there any way to assign a new object to a specific position (let's say the 5th position) of ptr_vector, directly? I'm looking for something like pv[5]=new Derived(5);. Any way of doing that?

最佳答案

ptr_vector::iterator 递增就像一个普通的随机访问迭代器。在您的示例中,您可以在不实际递增的情况下删除每个元素,因为在删除一个元素之后,它之后的每个元素都会在数组中移动。因此,当您删除第 0 个元素时,您的迭代器现在指向 曾经 作为第 1 个元素但现在是第 0 个元素的元素,依此类推。换句话说,迭代器停留在原地,而整个 vector 向左移动。

这与 ptr_vector 没有任何关系。请注意,使用普通 std::vector 会发生相同的行为。

另请注意,在删除它指向的元素后使用迭代器是危险的。在您的情况下它可以工作,但最好采用 ptr_vector::erase 的返回值,这样您就可以获得一个保证有效的新迭代器。

 for (it = pv.begin(); it != pv.end(); )
it = pv.erase(it);

关于您的其他问题:

如果你只想删除一个特定的元素,那么你当然应该直接使用pv.erase(pv.begin() + N)删除它。要为指针 vector 中的特定元素分配新值,只需说 pv[N] = Derived(whatever)。重新分配值时不需要使用 new。指针 vector 将在您将新值赋给的索引处调用对象的赋值运算符。

关于c++ - ptr_vector 迭代器不需要增量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4003292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com