#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循環不會遞增迭代器,但它會迭代和刪除所有元素。我的問題是:ptr_vector迭代器不需要增量嗎?
- 是我的迭代的技術,使用迭代是否正確?
- 如果for循環中不需要迭代器增量,那麼增量會在何處發生?
- 使用一個迭代器或將一個普通的整數是否更好(即:是否有使用迭代器的任何增值)? (因爲我也可以像pv.erase(pv.begin()+ 5)一樣擦除第五個元素;)
- 是否有任何方法將新對象分配給ptr_vector的特定位置(比方說第5個位置)直?我正在尋找像pv [5] = new Derived(5);的東西。任何方式做到這一點?
很酷!希望能回答問題3和4 :) – Nav 2010-10-23 09:59:19
沒有。我試過PV [0] =派生(888);並獲得此輸出:構造Derived888 boostPtrVsSTL:/usr/include/boost/ptr_container/ptr_sequence_adapter.hpp:325:typename boost :: ptr_container_detail :: reversible_ptr_container,CloneAllocator>: :引用boost :: ptr_sequence_adapter :: :: operator [](typename boost :: ptr_container_detail :: reversible_ptr_container –
Nav
2010-10-23 10:06:50
[continue ...],CloneAllocator> size_type)[with T = Derived,VoidPtrSeq = std :: vector>,CloneAllocator = boost :: heap_clone_allocator]:斷言'n < this-> size()'失敗。 Aborted(核心轉儲) –
Nav
2010-10-23 10:07:20