}
};

int main()
{
vector<Point> pointVec;
Point a;
Point b;
pointVec.push_back(a);
pointVec.push_back(b);

cout<<pointVec.size()<<std::endl;

return 0;
}
复制代码
输出结果:


其中执行

pointVec.push_back(a);
此时vector会申请一个内存空间,并调用拷贝构造函数将a放到vector中

再调用

pointVec.push_back(b);
此时内存不够 需要扩大内存,重新分配内存 这时再调用拷贝构造函数将a拷贝到新的内存,再将b拷入新的内存,同时有人调用Point拷贝构造函数,最后释放原来的内存 此时调用Point的析构函数。



2.vector的内存释放

由于vector的内存占用空间只增不减,比如你首先分配了10,000个字节,然后erase掉后面9,999个,留下一个有效元素,但是内存占用仍为10,000个。所有内存空间是在vector析构时候才能被系统回收。empty()用来检测容器是否为空的,clear()可以清空所有元素。但是即使clear(),vector所占用的内存空间依然如故,无法保证内存的回收。

如果需要空间动态缩小,可以考虑使用deque。如果vector,可以用swap()来帮助你释放内存。具体方法如下:

vector<Point>().swap(pointVec); //或者pointVec.swap(vector<Point> ())
标准模板:

复制代码
template < class T >
void ClearVector( vector< T >& vt )
{
vector< T > vtTemp;
veTemp.swap( vt );
}
复制代码
swap()是交换函数,使vector离开其自身的作用域,从而强制释放vector所占的内存空间,总而言之,释放vector内存最简单的方法是vector<Point>().swap(pointVec)。当时如果pointVec是一个类的成员,不能把vector<Point>().swap(pointVec)写进类的析构函数中,否则会导致double free or corruption (fasttop)的错误,原因可能是重复释放内存。(前面的pointVec.swap(vector<Point> ())用G++编译没有通过)



3.其他情况释放内存

如果vector中存放的是指针,那么当vector销毁时,这些指针指向的对象不会被销毁,那么内存就不会被释放。如下面这种情况,vector中的元素时由new操作动态申请出来的对象指针:

#include <vector>
using namespace std;

vector<void *> v;
每次new之后调用v.push_back()该指针,在程序退出或者根据需要,用以下代码进行内存的释放:

复制代码
for (vector<void *>::iterator it = v.begin(); it != v.end(); it ++)
if (NULL != *it)
{
delete *it;
*it = NULL;
}
v.clear();
 
 
vector being faster to build or clear than deque or list is to be expected; it's a simpler data structure.

With regard to vector::push_back, it has to do two things:

check the vector is big enough to hold the new item.
insert the new item.
You can generally speed things up by eliminating step 1 by simply resizing the vector and using operator[] to set items.

UPDATE: Original poster asked for an example. The code below times 128 mega insertions, and outputs

push_back : 2.04s
reserve & push_back : 1.73s
resize & place : 0.48s
when compiled and run with g++ -O3 on Debian/Lenny on an old P4 machine.
#include <iostream> 
#include <time.h> 
#include <vector> 
  
int main(int,char**) 
{ 
  const size_t n=(128<<20); 
  
  const clock_t t0=clock(); 
  { 
    std::vector<unsigned char> a; 
    for (size_t i=0;i<n;i++) a.push_back(i); 
  } 
  const clock_t t1=clock(); 
  { 
    std::vector<unsigned char> a; 
    a.reserve(n); 
    for (size_t i=0;i<n;i++) a.push_back(i); 
  } 
  const clock_t t2=clock(); 
  { 
    std::vector<unsigned char> a; 
    a.resize(n); 
    for (size_t i=0;i<n;i++) a[i]=i; 
  } 
  const clock_t t3=clock(); 
  
  std::cout << "push_back           : " << (t1-t0)/static_cast<float>(CLOCKS_PER_SEC) << "s" << std::endl; 
  std::cout << "reserve & push_back : " << (t2-t1)/static_cast<float>(CLOCKS_PER_SEC) << "s" << std::endl; 
  std::cout << "resize & place      : " << (t3-t2)/static_cast<float>(CLOCKS_PER_SEC) << "s" << std::endl; 
  
  return 0;   
} 

 

相关文章: