special.cpp

来自「Thinking in C++ 2nd edition source code 」· C++ 代码 · 共 46 行

CPP
46
字号
//: C16:Special.cpp
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// Template specialization
// A special sort for char*
#include <iostream>
#include "Sorted.h"
using namespace std;

// Specialize the class template:
class Sorted<char> :  public TStash<char> {
  void bubblesort();
public:
  int add(char* element) {
    TStash<char>::add(element);
    bubblesort();
    return 0; // Sort moves the element
  }
};

void Sorted<char>::bubblesort() {
  for(int i = count(); i > 0; i--)
    for(int j = 1; j < i; j++)
      if(strcmp(storage[j], storage[j-1]) < 0) {
        // Swap the two elements:
        char* t = storage[j-1];
        storage[j-1] = storage[j];
        storage[j] = t;
      }
}

char* words[] = {
  "is", "running", "big", "dog", "a",
};
const int wsz = sizeof words/sizeof *words;

int main() {
  Sorted<char> sc;
  for(int k = 0; k < wsz; k++)
    sc.add(words[k]);
  for(int l = 0; l < sc.count(); l++)
    cout << sc[l] << endl;
} ///:~

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?