📄 sorted.h
字号:
//: C16:Sorted.h
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// Template inheritance
#ifndef SORTED_H_
#define SORTED_H_
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <vector>
#include "TStash.h"
template<class T>
class Sorted : public TStash<T> {
void bubblesort();
public:
int add(T* element) {
TStash<T>::add(element);
bubblesort();
return 0; // Sort moves the element
}
};
template<class T>
void Sorted<T>::bubblesort() {
for(int i = count(); i > 0; i--)
for(int j = 1; j < i; j++)
if(*storage[j-1] > *storage[j]) {
// Swap the two elements:
T* t = storage[j-1];
storage[j-1] = storage[j];
storage[j] = t;
}
}
// Unique random number generator:
template<int upper_bound>
class Urand {
int map[upper_bound];
int recycle;
public:
Urand(int Recycle = 0);
int operator()();
};
template<int upper_bound>
Urand<upper_bound>::Urand(int Recycle)
: recycle(Recycle) {
memset(map, 0, upper_bound * sizeof(int));
srand(time(0)); // Seed random number generator
}
template<int upper_bound>
int Urand<upper_bound>::operator()() {
if(!memchr(map, 0, upper_bound)) {
if(recycle)
memset(map, 0,
sizeof(map) * sizeof(int));
else
return -1; // No more spaces left
}
int newval;
while(map[newval = rand() % upper_bound])
; // Until unique value is found
map[newval]++; // Set flag
return newval;
}
#endif // SORTED_H_ ///:~
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -