vector预留空间(reserve)

#include <iostream>
#include <vector>
using namespace std;

#define NUM 10000

int main()
{
   vector<int> v;
   int *p = NULL;
   int num = 0;

   for(int i = 0; i < NUM; i++)
   {
      v.push_back(i);

      if(p != &v[0])
      {
         p = &v[0];
         num++;
      }
   }

   cout << "num " << num << endl;

   return 0;
}
$ ./a.out 
num 15
#include <iostream>
#include <vector>
using namespace std;

#define NUM 10000

int main()
{
   vector<int> v;
   int *p = NULL;
   int num = 0;

   v.reserve(NUM);

   for(int i = 0; i < NUM; i++)
   {
      v.push_back(i);

      if(p != &v[0])
      {
         p = &v[0];
         num++;
      }
   }

   cout << "num " << num << endl;

   return 0;
}
$ ./a.out 
num 1
posted @ 2022-07-27 20:43  thomas_blog  阅读(69)  评论(0编辑  收藏  举报