#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 循环不会增加迭代器,但它会迭代并擦除所有元素。我的问题是:
- 我的迭代技术和使用迭代器是否正确?
- 如果 for 循环中不需要迭代器增量,那么增量发生在哪里?
- 使用迭代器更好还是普通整数就足够了(即:使用迭代器是否有任何增值)?(因为我也可以像 pv.erase(pv.begin()+5); 一样擦除第 5 个元素;)
- 有没有办法直接将新对象分配给 ptr_vector 的特定位置(比如说第 5 个位置)?我正在寻找类似 pv[5]=new Derived(5); 的东西。有什么办法吗?