Posts tagged ‘stl’

记录一种删除容器最快办法

for (iterator iter = value.begin(); iter != value.end(); )
{
   if (xxx)
      value.erase(iter++);
   else
      iter++;
}

该方法不适用于vector,原因是官网有一句:

Because vectors use an array as their underlying storage, erasing elements in positions other than the vector endcauses the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).

因此要用下面的方法:

for (iterator iter = value.begin(); iter != value.end(); )
{
   if (xxx)
      iter = value.erase(iter);
   else
      iter++;
}

标准C++中的STL容器类简介

转自:http://blog.csdn.net/phunxm/archive/2009/12/26/5081472.aspx

SGI — Silicon Graphics[Computer System] Inc.硅图[计算机系统]公司.

STL — Standard Template Library 标准模板库。

容器的概念

所谓STL容器,即是将最常运用的一些数据结构(data structures)实现出来。

容器是指容纳特定类型对象的集合。根据数据在容器中排列的特性,容器可概分为序列式(sequence)和关联式(associative)两种。

迭代器是一种检查容器内元素并遍历元素的数据类型。它提供类似指针的功能,对容器的内容进行走访。

#include<iterator>

例如:

std::vector<int> IntVector;

std::vector<int>::iterator first=IntVector.begin();

// begin()得到指向vector开头的Iterator,*first得到开头一个元素的值

std::vector<int>::iterator last=IntVector.end();

// end()得到指向vector结尾的Iterator,*last得到最后一个元素的值

  Continue reading ‘标准C++中的STL容器类简介’ »