C++编程思想 第2卷 第7章 通用容器 基本序列容器:vector list deque 链表

list以一个双向链表数据结构来实现
如此设计是为了在一个序列的任何地方快速地插入或删除元素
对于vector和deque而言是一个代价高得多的操作

//: C07:ListStability.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.
// Things don't move around in lists.
//{L} Noisy
#include <algorithm>
#include <iostream>
#include <iterator>
#include <list>
#include "Noisy.h"
using namespace std;

int main() {
  list<Noisy> l;
  ostream_iterator<Noisy> out(cout, " ");
  generate_n(back_inserter(l), 25, NoisyGen());
  cout << "\n Printing the list:" << endl;
  copy(l.begin(), l.end(), out);
  cout << "\n Reversing the list:" << endl;
  l.reverse();
  copy(l.begin(), l.end(), out);
  cout << "\n Sorting the list:" << endl;
  l.sort();
  copy(l.begin(), l.end(), out);
  cout << "\n Swapping two elements:" << endl;
  list<Noisy>::iterator it1, it2;
  it1 = it2 = l.begin();
  ++it2;
  swap(*it1, *it2);
  cout << endl;
  copy(l.begin(), l.end(), out);
  cout << "\n Using generic reverse(): " << endl;
  reverse(l.begin(), l.end());
  cout << endl;
  copy(l.begin(), l.end(), out);
  cout << "\n Cleanup" << endl;
  getchar();
} ///:~


输出
d[0]
c[0]
~[0]
d[1]
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]
d[10]
c[10]
~[10]
d[11]
c[11]
~[11]
d[12]
c[12]
~[12]
d[13]
c[13]
~[13]
d[14]
c[14]
~[14]
d[15]
c[15]
~[15]
d[16]
c[16]
~[16]
d[17]
c[17]
~[17]
d[18]
c[18]
~[18]
d[19]
c[19]
~[19]
d[20]
c[20]
~[20]
d[21]
c[21]
~[21]
d[22]
c[22]
~[22]
d[23]
c[23]
~[23]
d[24]
c[24]
~[24]

 Printing the list:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 Reversing the list:
24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
 Sorting the list:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 Swapping two elements:
c[0]
(0)=[1]
(1)=[0]
~[0]

1 0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 Using generic reverse():
c[1]
(1)=[24]
(24)=[1]
~[1]
c[0]
(0)=[23]
(23)=[0]
~[0]
c[2]
(2)=[22]
(22)=[2]
~[2]
c[3]
(3)=[21]
(21)=[3]
~[3]
c[4]
(4)=[20]
(20)=[4]
~[4]
c[5]
(5)=[19]
(19)=[5]
~[5]
c[6]
(6)=[18]
(18)=[6]
~[6]
c[7]
(7)=[17]
(17)=[7]
~[7]
c[8]
(8)=[16]
(16)=[8]
~[8]
c[9]
(9)=[15]
(15)=[9]
~[9]
c[10]
(10)=[14]
(14)=[10]
~[10]
c[11]
(11)=[13]
(13)=[11]
~[11]

24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 0 1
 Cleanup

对于list 像进行逆转和排序看起来激进的操作不需要拷贝对象
因为 仅需要改变链接而不是移动对象
要注意sort()和reverse()都是list的成员函数
所有它们有list内在特殊知识
能够以再排列元素来代替拷贝它们

猜你喜欢

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