C++编程思想 第2卷 第7章 通用容器 基本序列容器:vector list deque 序列容器间的转换

有时在程序的某一部分需要某一种容器的行为或效率
而在程序的另一部分则需要不同容器的行为或效率

将对象读入deque内
然后将其转换到一个vector

//: C07:DequeConversion.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.
// Reading into a Deque, converting to a vector.
//{L} Noisy
#include <algorithm>
#include <cstdlib>
#include <deque>
#include <iostream>
#include <iterator>
#include <vector>
#include "Noisy.h"
using namespace std;

int main(int argc, char* argv[]) {
  int size = 25;
  if(argc >= 2) size = atoi(argv[1]);
  deque<Noisy> d;
  generate_n(back_inserter(d), size, NoisyGen());
  cout << "\n Converting to a vector(1)" << endl;
  vector<Noisy> v1(d.begin(), d.end());
  cout << "\n Converting to a vector(2)" << endl;
  vector<Noisy> v2;
  v2.reserve(d.size());
  v2.assign(d.begin(), d.end());
  cout << "\n Cleanup" << endl;
  getchar();
} ///:~


输出

 Converting to a vector(2)
c[0]
c[1]
c[2]
c[3]
c[4]
c[5]
c[6]
c[7]
c[8]
c[9]
c[10]
c[11]
c[12]
c[13]
c[14]
c[15]
c[16]
c[17]
c[18]
c[19]
c[20]
c[21]
c[22]
c[23]
c[24]

 Cleanup
 
可以尝试各种尺寸大小的容器,但没差别
这些对象仅被拷贝构造到新的vector中去
在构建vector是v1并不会导致多次内存分配
不管使用多少元素都是这样 

猜你喜欢

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