C++ STL 嵌套容器释放问题

  最近操作stl 容器,发现自己对stl操作理解还不是很深。这边定义了下面的嵌套vector的容器,自己对其释放时做的工作。

  数据结构类型:

typedef struct csvdata_t
{
     string  datetime;
     double  temperature;
}csvdata;

vector< vector > csv_data;

 最终销毁数据:因为vector里面嵌套vector所以要做双重释放,vector< vector >::iterator pos; 为第一层迭代器,迭代器在c++实际实现为指针。即使用指针访问对应索引的对象。为了更加直观简便的使用迭代器,各个迭代器均对该指针重载了"->"和"*"解引用操作符,所以pos即为指针,指向vector元素的地址。 在定义vector的迭代器std::vector::iterator inos;  inos指向的csvdata *类型,对其解引用"*",才是其真正的类型,真正类型为csvdata *,为动态申请内容,需释放delete(*inos); 其中pos->erase(pos->begin(), pos->end());和 allin.erase(allin.begin(), allin.end()); 为清空vector容器中所有内容。

 void destory_csvdata(vector< vector >& allin)
 {
    int i = 0;
    vector< vector >::iterator pos; 	
    for(pos = allin.begin(); pos != allin.end(); ++pos)
    {
         std::vector::iterator inos;
         for(inos = pos->begin(); inos != pos->end(); ++inos)
         {
               //log("free--------%d",++i);
               delete (*inos);
         }
         pos->erase(pos->begin(), pos->end()) ; 
    }
    allin.erase(allin.begin(), allin.end());
 }

你可能感兴趣的:(#,C/C++,组件,技巧,c++)