C++编程思想 第2卷 第6章 通用算法 STL算法目录 对已排序的序列进行排序和运算 合并已排序的序列

在合并中使用int类型
数组和容器一起工作

 

还有PrintSequence.h  Generators.h就不贴了

//: C06:MergeTest.cpp
// 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.
// Test merging in sorted ranges.
//{L} Generators
#include <algorithm>
#include "PrintSequence.h"
#include "Generators.h"
using namespace std;

int main() {
  const int SZ = 15;
  int a[SZ*2] = {0};
  // Both ranges go in the same array:
  generate(a, a + SZ, SkipGen(0, 2));
  a[3] = 4;
  a[4] = 4;
  generate(a + SZ, a + SZ*2, SkipGen(1, 3));
  print(a, a + SZ, "range1", " ");
  print(a + SZ, a + SZ*2, "range2", " ");
  int b[SZ*2] = {0}; // Initialize all to zero
  merge(a, a + SZ, a + SZ, a + SZ*2, b);
  print(b, b + SZ*2, "merge", " ");
  // Reset b
  for(int i = 0; i < SZ*2; i++)
    b[i] = 0;
  inplace_merge(a, a + SZ, a + SZ*2);
  print(a, a + SZ*2, "inplace_merge", " ");
  int* end = set_union(a, a + SZ, a + SZ, a + SZ*2, b);
  print(b, end, "set_union", " ");
  getchar();
} ///:~


输出
range1:  0 2 4 4 4 10 12 14 16 18 20 22 24 26 28
range2:  1 4 7 10 13 16 19 22 25 28 31 34 37 40 43
merge:  0 1 2 4 4 4 4 7 10 10 12 13 14 16 16 18 19 20 22 22 24 25 26 28 28 31 34 37 40 43
inplace_merge:  0 1 2 4 4 4 4 7 10 10 12 13 14 16 16 18 19 20 22 22 24 25 26 28 28 31 34 37 40 43
set_union:  0 1 2 4 4 4 4 7 10 10 12 13 14 16 16 18 19 20 22 22 24 25 26 28 28 31 34 37 40 43

在main()中,不是创建两个独立的数组
而是在数组a中创建两个首尾相连的范围
第1个merge()的调用把结果放入一个不同的数组b中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值