C++编程思想 第2卷 第7章 通用容器 基本序列容器:vector list deque 向量 插入和删除元素


使用vector最有效的条件
1 在开始时用reserve()分配了正确数量的存储区
因此vector绝不再重新分配存储 区
2 仅仅在序列的后端添加或删除元素

利用一个迭代器向vector中间插入或者删除元素是可能的
但程序演示了一个糟糕的想法

//: C07:VectorInsertAndErase.cpp {-bor}
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Erasing an element from a vector.
//{L} Noisy
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include "Noisy.h"
using namespace std;

int main() {
  vector<Noisy> v;
  v.reserve(11);
  cout << "11 spaces have been reserved" << endl;
  generate_n(back_inserter(v), 10, NoisyGen());
  ostream_iterator<Noisy> out(cout, " ");
  cout << endl;
  copy(v.begin(), v.end(), out);
  cout << "Inserting an element:" << endl;
  vector<Noisy>::iterator it =
    v.begin() + v.size() / 2; // Middle
  v.insert(it, Noisy());
  cout << endl;
  copy(v.begin(), v.end(), out);
  cout << "\nErasing an element:" << endl;
  // Cannot use the previous value of it:
  it = v.begin() + v.size() / 2;
  v.erase(it);
  cout << endl;
  copy(v.begin(), v.end(), out);
  cout << endl;
  getchar();
} ///:~


输出
c[1]
~[1]
d[2]
c[2]
~[2]
d[3]
c[3]
~[3]
d[4]
c[4]
~[4]
d[5]
c[5]
~[5]
d[6]
c[6]
~[6]
d[7]
c[7]
~[7]
d[8]
c[8]
~[8]
d[9]
c[9]
~[9]

0 1 2 3 4 5 6 7 8 9 Inserting an element:
d[10]
c[10]
c[6]
(6)=[5]
(5)=[6]
~[6]
c[6]
(6)=[10]
(10)=[6]
~[6]
c[6]
(6)=[9]
(9)=[6]
~[6]
c[6]
(6)=[8]
(8)=[6]
~[6]
c[6]
(6)=[7]
(7)=[6]
~[6]
~[10]

0 1 2 3 4 10 5 6 7 8 9
Erasing an element:
(10)=[5]
(5)=[6]
(6)=[7]
(7)=[8]
(8)=[9]
~[9]

0 1 2 3 4 5 6 7 8 9

运行该程序 可以看到
对预分配函数reserve()的 调用实际上仅仅是分配存储区
并没有调用构造函数
对generate_n()的调用非常频繁

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/82347461