一些零碎代码
**
關于源文件與頭文件:代碼:頭文件代碼
**:#includenamespace pers {
struct person {
std::string fname;
std::string lname;};
?
void getperson(person&);
void show(const person&);}
namespace debts {
using namespace pers;
struct debt {
person name;
double amount;
};
void getdebt(debt&);
void showdebt(const debt&);
double sum(const debt ar[], int n);}源文件(兩個):第一個:通過包含頭文件,導入了原來的名稱空間,然后該文件將函數定義添加到兩個名稱空間中。#include
#include “源.cpp"using namespace debts;
namespace pers {
using std::cout;
using std::cin;
void getperson(person& rp) {
cout << “enter fname”;
cin >> rp.fname;
cin >> rp.lname;
}
void show(const person & rp) {
cout << rp.fname;
cout << rp.lname << “\t”; }
? }
namespace debts {void getdebt(debt&rp) {
getperson(rp.name);
cout << “please enter debt”;
cin >> rp.amount;}
void showdebt(const debt&rp)
{
show(rp.name);
cout << rp.amount;
}double sum(const debt ar[], int n) {
double am = 0;
for (int i = 0; i < n; i++)
am += ar[i].amount;
return am;
?
}}第二個:含有主函數main#include
#include"源.cpp”
void other(void);
void another(void);
using namespace std;
using namespace pers;
using namespace debts;
int main() {
debt golf = { {“ben”,“jieming”},32.1 };
showdebt(golf);
other();}
void other() {
person dg = { “ii”,“derw” };
show(dg);
cout << endl;
debt dogg[3];
int i;
for (i = 0; i < 3; i++)
getdebt(dogg[i]);
for (i = 0; i < 3; i++)
showdebt(dogg[i]);
cout << “tatol debt $” << sum(dogg, 3);}
關于從鍵盤正確輸入一個東西并檢查是否合法
include
double x;
int main() {
std::cout << “enter!”;
while (!(std::cin >> x))
{
std::cout << “should double”;
std::cin.clear();
while (std::cin.get() != ‘\n’)
continue;
} std:: cout << “the value is” << x;
}
關于排列:定義一個描述三種顏色的枚舉類型,編程輸出這三種顏色的全排列
include
using namespace std;
enum color{red,blue,green};
enum color pri;
int n,i, j, k, loop;
int main()
{
n = 0;
for (i = red ;i <= green ;i++)
for (j = red; j <= green; j++) {
for (k = red; k <= green; k++)
if (i != j)
{
if ((k != i) && (k != j))
{
n++;
cout << n << “:”; for (loop = 1; loop <= 3; loop++)
{
switch (loop)
{
case(1):pri = (enum color)i; break;
case(2):pri = (enum color)j; break;
case(3):pri = (enum color)k; break;
}
switch (pri)
{
case(red):cout << "red "; break;
case(blue):cout << "blue "; break;
case(green):cout << "green "; break;
}
關于將一個數組移位:先寫一個函數向右移動一位,再寫一個函數調用前面的函數移動n位
。#includeusing namespace std;
void move(int p[], int n)
{
int t;
t = p[n - 1];
if (n == 0) return;
for (int i = n-1; i > 0; i–)//注意i的取值
{
p[i] = p[i - 1];
}
p[0] = t;}
void movep(int p[], int k, int n)
{
for (int i = 0; i < k; i++)
move(p, n);//調用move函數移動k位
}
int main() {
int p[5];
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> p[i];
}
for (int i = 0; i < n; i++)
{
cout << p[i];
}
int k;
cout << “the k:”;
cin >> k;
movep(p, k, n);
cout << “after:”;
for (int i = 0; i < n; i++)
cout << p[i];}
輸入字符串,調用函數取出字符串中最長的單詞并存入另一個字符串。
(有待思考)#define _CRT_SECURE_NO_WARNINGS
#include
#include
#includeusing namespace std;
void index(char* s1, char* s2)
{
int len ,max = 0;
char temp[50];
while (*s1)
{
while (*s1 == ’ ’ && *s1 != ‘\0’) s1++;//過濾空格;
}}
int main()
{
char s1[50],s2[50];cin.get(s1,50); index(s1, s2);
? cout << “s2:” << s2;
}用隊列的方法輸出楊輝三角:#include
using namespace std;
const int maxsize = 100;
typedef struct {
int Q[maxsize];//存放數據
int front, rear;
}sequeue;
sequeue qu;
void setkong(sequeue& qq)
{
qq.front = 0;
qq.rear = 0;
}//置隊空
void rudui(sequeue& qq, int x)
{
if (qq.front == (qq.rear + 1) % maxsize)
cout << “overflow\n”;
else
{
qq.Q[qq.rear] = x;
qq.rear = (qq.rear + 1) % maxsize;
}
}
void chudui(sequeue &qq, int& x)
{
if (qq.front == qq.rear)
{
cout << “underflow\n”;
}
else
{
x = qq.Q[qq.front];
qq.front = (qq.front + 1) % maxsize;
}
}
void getfront(sequeue qq, int &x)//讀取隊頭元素
{
if (qq.front == qq.rear)
{
cout << “error!\n”;
}
?
else
{
x = qq.Q[qq.front];
}
}
int empty(sequeue qq)//判斷隊列是否為空
{
if (qq.front == qq.rear)
return 1;
else
return 0;
}
void yanghui(int n,sequeue qu)
{
int i, j,s,t;
setkong(qu);
rudui(qu, 1); rudui(qu, 1);
cout << endl;
cout.width(4); cout << 1;
cout.width(4); cout << 1<<endl;
for (i = 2; i <= n; i++)//生成并輸出楊輝三角第i~n行的數據
{
rudui(qu, 1);
cout.width(4); cout << 1;
chudui(qu, s);
for (j = 2; j <= i; j++)//處理第i行中間的各數據
{
chudui(qu, t);
rudui(qu, s + t);
cout.width(4); cout << s + t;
s = t;
?
?
}
int main()
{
int m;
cin >> m;
yanghui(m, qu);
}
最長的不重復的字符子串
include
#include
#include<unordered_set>
using namespace std;
int lengthOfLongestSubstring(string s);
?
int lengthOfLongestSubstring(string s)
{
// 哈希集合,記錄每個字符是否出現過
unordered_set occ;
int n = s.size();
// 右指針,初始值為 -1,相當于我們在字符串的左邊界的左側,還沒有開始移動
int rk = -1, ans = 0;
// 枚舉左指針的位置,初始值隱性地表示為 -1
for (int i = 0; i < n; ++i)
{
if (i != 0)
{
// 左指針向右移動一格,移除一個字符
occ.erase(s[i - 1]);
}
while (rk + 1 < n && !occ.count(s[rk + 1]))
{
// 不斷地移動右指針
occ.insert(s[rk + 1]);
++rk;
}
// 第 i 到 rk 個字符是一個極長的無重復字符子串
ans = max(ans, rk - i + 1);
}
return ans;
};
int main() {
string mm;
cin >> mm;
int num;
num = lengthOfLongestSubstring(mm);
cout << num;
}
?
?
彩票案例
(二維數組初始化)//彩票案例
//隨機生成1-49之間的蘇子 程序中每一組中按照升序排序
//檢查某個數字在用戶選擇的所有彩票中出現的次數
//七行六列隨機數
//注意初始化二維數組 int table = new int**[7]
//int table[i] = new int*[6]
//下標越界時會導致錯誤
#include
#include
#include
using namespace std;
const int column = 6;
const int maxx = 49;
void iniarray(int**, int);
int isnum(int**, int, int);
void sort(int**, int);
void print(int**);
int numoccur(int** table, int mm);
inline void memerror() {
cout << “error\n”;
exit(1);
}
void genloto(int**, int);
int main() {
int** table;
int numcheck;
int i;
int client;
char answer;
srand((unsigned)time(0));
table = new int* [7];
if (!table)
memerror();
for (i = 0; i < 7; i++) {
table[i] = new int[6];
if (!table[i])
memerror();//check for an allocation error
}
iniarray(table, 7);
genloto(table, 7);
for (i = 0; i < 7; i++)
{
sort(table, i);//sort numbers in a row
}
print(table);
cin >> client;//用戶輸入數字
numcheck = numoccur(table, client);
cout << "the num = " << numcheck;
}
void iniarray(inttable, int)
{
int i, j;
for (i = 0; i < 7; i++)
{
for (j = 0; j < 6; j++)
table[i][j] = 0;
}
}
?
void genloto(inttable, int)
{
int i, j;
int newnum;
for (i = 0; i < 7; i++) {
for (j = 0; j < 6; j++)
{
do
{
newnum = rand() % maxx + 1;
} while (isnum(table, i, newnum));
table[i][j] = newnum;
}
}
}
int isnum(int**table, int num, int n) {
for (int i = 0; i < 6; i++) {
if (table[num][i] == 0)
return 0;
if (table[num][i] == n)
return 1;
?
}
return 0;
}
//
升序排列的代碼
void sort(int** table, int row) {
int temp;
for (int i = 0; i < 5; i++) {//注意i j 一定不能大于5
for (int j = 0; j < 5; j++)
{
if (table[row][j] > table[row][j + 1])
{
temp = table[row][j];
table[row][j] = table[row][j + 1];
table[row][j + 1] = temp;
}
?
}
}
}
void print(inttable)
{
cout << endl;
cout << "**\n";
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 6; j++)
cout << table[i][j] << “\t”;
cout << endl;
}
?
}
int numoccur(int table, int num) {
int count = 0;
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 6; j++)
{
if (table[i][j] == num)
count++;
}
}
return count;
}
銀行賬戶管理系統
include
#include
using namespace std;
class saving {
private:
int id;
double balance;//余額
double rate;//年利率
int lastdate;//上次變更余額的時期
double accumulation;//余額按日期累加之和
void record(int date, double amount);
double accumulate(int date) const {
return accumulation + balance * (date - lastdate);
}
public:
saving(int date, int id, double rate);//構造函數
int getid() { return id; }
double getbalance() { return balance; }
double getrate() { return rate; }
void deposit(int date, double amount);//存入現金
void withdraw(int date, double amount);//取出現金
void settle(int date);//結算利息
void show();//顯示賬號信息
};
saving::saving(int date, int id, double rate):id(id),balance(0),rate(rate),lastdate(date),accumulation(0)
{
cout << id << “is created\n”;
}
void saving::record(int date, double amount)
{
accumulation = accumulate(date);
lastdate = date;
amount = floor(amount * 100 + 0.5) / 100; //保留小數點后兩位
balance += amount;
cout << date << “—” << id <<“amount:”<< amount<<“balance:” << balance;
}
void saving::deposit(int date, double amount)
{
record(date, amount);
}
void saving:: withdraw(int date, double amount)
{
if (getbalance() < 0)
cout << “error\n”;
else
record(date, -amount);
}
void saving:: settle(int date)
{
double interest = accumulate(date) * rate / 365;
if (interest != 0)
record(date, interest);
accumulation = 0;
}
void saving::show()
{
cout << id << balance;
}
int main()
{
saving s1(1, 4234, 0.15);
s1.deposit(3, 5000);
s1.show();
s1.deposit(5, 3000);
cout << endl;
s1.show();
cout << endl;
s1.settle(80);
s1.show();
cout << endl;
}
容器嵌套#include
#include
#include
using namespace std;
void test()
{
vector<vector> mm;
vectorp1;
vectorp2;
vectorp3;
vectorp4;
for (int i = 0; i < 4; i++)
{
p1.push_back(i);
p2.push_back(i + 1);
p3.push_back(i + 2);
p4.push_back(i + 3);
}
mm.push_back(p1);
mm.push_back(p2);
mm.push_back(p3);
mm.push_back(p4);
for (vector<vector>::iterator mg = mm.begin(); mg != mm.end(); mg++)
}
int main()
{
test();
}
訪問單個字符:string str = “hello”;for(int i = 0;i < str.size() ;i++)cout<<str[i];
多態性變步長梯形積分
include
class function//抽象類function的定義
{
public:
virtual double operator()(double x) const = 0;//純虛函數重載運算符()
virtual ~function() {};
};
class myfunction :public function {
public:
double operator()(double x) const;//覆蓋虛函數
};
class integrate {
public:
virtual double operator()(double a, double b, double eps)const = 0;
virtual ~integrate() {}
};
class grate :public integrate {
public:
double operator()(double a, double b, double eps)const;
grate(function&mm):f(mm){}//構造函數
private:
function& f;//私有成員
};
//類實現
double myfunction::operator()(double x) const {
return log(1.0 + x) / (1.0 + x * x);
}
double grate::operator()(double a, double b, double eps)const
{
myfunction yy;
grate nice(yy);
bool judge = false;
double h = b - a;
double tn = (yy(a) + yy(b)) * h / 2;
double t2n;
int n = 1;
do{
double sum = 0;
for (int k = 0; k < n; k++) {
double x = a + (k + 0.5) * h;
sum += f(x);
}
t2n = (tn + h * sum) / 2.0;//變步長梯形法計算
if (fabs(t2n - tn) < eps)//判斷積分誤差
judge = true;
else
{
tn = t2n;
n *= 2;
h /= 2;
}
} while (!judge);
return t2n;
}
array類模板(重載指針下標運算符 等號)trap.h:動態數組類模板array
#include
template
class Array {
T* mm;//T類型指針 用于存放動態分配的數組首地址
int size;//數組大小
public:
Array(int siz = 50);
Array(const Array& yy);//復制構造函數
~Array();
Array& operator = (Array& rhs);//重載“=”
T& operator [](int i);//重載[];
operator T* ();
//重載指針轉化運算符T* 要想對象名能像數組名一樣使用下標,還要重載下標運算符
int getsize()const;
void resize(int sz);//修改數組大小
};
template
Array::Array(int siz)
{
assert(siz >= 0);
size = siz;
mm = new T[size];//動態分配size個T類型的元素空間
}
template
Array& Array:: operator = (Array& rhs)
//重載“=” 將對象rhs賦給本對象 實現對象之間整體賦值
{
if (size != rhs.size) {//如果本對象中數組大小與rhs不同 則刪除數組原有內存然后重新分配
}
template
Array::~Array()
{
delete[]mm;
}
template
Array::operator T* ()
{
return mm;//返回當前對象中私有數組的首地址
}
template
T& Array:: operator [] (int i)
{
assert(i >= 0 && i < size);//檢查下標是否越界
return mm[i];
}
template
int Array::getsize()const
{
return size;
}
template
void Array::resize(int sz)
{
assert(sz >= 0);//檢查sz是否非負
if (size == sz)
return;//如果指定的大小與原有大小一樣什么也不做
T* newlist = new T[sz];//申請新的內存
int n = (sz < size) ? sz : size;//將sz 與size中較小的值賦給n
for (int i = 0; i < n; i++)
{
newlist[i] = mm[i];//將原有數組的前n個元素復制到新數組中
}
delete[] mm;//刪除原數組
mm = newlist;//使mm指向新數組
size = sz;//更新size
}
從鍵盤輸入n,計算2~n中的質數并且輸出
:#include
#include"trap.h"
#include
using namespace std;
int main()
{
int n;
cin >> n;
int count = 0;
Arraynice(10);
int i;
}//個人認為a[0]一開始應該是一個隨機數
vector構造函數//奇偶排序 先奇數再偶數 從大到小的順序
#include
#include
#include
#include
#include
using namespace std;
int main()
{
istream_iterators1(cin), s2;//建立一對輸入流迭代器
vector i1(s1, s2);//通過輸入流迭代器從標準輸入流中輸入數據
sort(i1.begin(), i1.end());//將輸入的整數排序
dequem1;
//循環遍歷i1
for (vector::iterator ite = i1.begin(); ite != i1.end(); ++ite)
{
if (*ite % 2 == 0)//偶數放m1尾部
m1.push_back(*ite);
else
m1.push_front(*ite);
}
copy(m1.begin(), m1.end(), ostream_iterator(cout, “-”));//輸出結果 以-符號分隔
}
結點類模板#include
using namespace std;
//結點類模板
template
class node {
private:
node* next;//指向后繼結點的指針
public:
T data;//數據域
node(const T& data, node* next = 0);//構造函數
void insert(node* p);//在本結點之后插入一個同類結點
node* deleteafter();//刪除本結點的后繼結點并且返回其地址
node* getlocation();//獲取后繼結點的地址
const node* getlocation() const;//獲取后繼結點的地址
};
//類的實現部分
template
node::node(const T& data, node* next ):data(data),next(next){}
template
void node::insert(node* p)
{
p->next = next;//p的指針域指向當前結點的后繼結點
next = p;//當前結點指針域指向p
}
template
nodenode:: deleteafter()
{
node temp;
temp = next;//將欲刪除的結點地址存儲在temp中
if (next == 0)//如果當前結點沒有后繼結點 返回空指針
return 0;
next = temp->next;//使當前結點指向temp的后繼結點
return temp;//返回被刪除的結點的地址
}
template
node* node::getlocation()
{
return next;//返回后繼結點的指針
}
template
const node* node::getlocation() const
{
return next;
}
細胞分裂
:#include
#include
#include
#include
using namespace std;
const int maxx = 2000;
const int minn = 500;
class cell;
priority_queuecellque;
class cell {
private:
static int total;//細胞總數
int id;//當前細胞編號
int time;//細胞分裂時間
public:
cell(int birth) :id(total++) { time = birth + (rand() % (maxx - minn) )+ minn; }
//初始化獲得細胞分裂時間
int getid() const{ return id; }//獲取細胞編號
int gettime() const{ return time; }//獲取細胞分裂時間
bool operator <(const cell& s)const { return time > s.time; }//定義"<"
void spilit()const
{
cell xibao1(time), xibao2(time);//得到兩個細胞
cout << time << “cell” << id << “splits to” << xibao1.getid() << " " << xibao2.getid() << endl;
cellque.push(xibao1);//將第一個子細胞壓入優先級隊列
cellque.push(xibao2);//
};
int cell::total = 0;
int main()
{
srand(static_cast(time(0)));
int t;
cout << “input\n”;
cin >> t;
cellque.push(cell(0));
while (cellque.top().gettime() <= t)
{
cellque.top().spilit();
cellque.pop();
}
}
//棧操作#include
#include
using namespace std;
template<class T, int size = 50>
class stack {
private:
T list[size];
int top;
public:
stack();
void push(const T& mm){
assert(!isfull());//如果棧滿了則報錯
list[++top] = mm;//將新元素壓入棧頂
}
T pop()//將棧頂元素彈出棧
{
assert(!isempty());
return list[top–];//返回棧頂元素并將其彈出棧
}
void clear()
{
top = -1;//清空棧
}
const T& peek()const//訪問棧頂元素
{
assert(!isempty());//如果為空則報錯
return list[top];
}
bool isempty()const
{
return top == -1;
}
bool isfull()const
{
return top == size - 1;
}
};
template<class T, int size>
stack<T, size>::stack() :top(-1) {};//構造函數 棧頂初始化為-1.class cal {
stacks;
void enter(double num)
{
s.push(num);
}//操作數彈出棧 如果棧中沒有兩個操作數則返回錯誤信息
bool gettwo(double& o1, double& o2)
{
bool mod;
if (s.isempty())
{
cout << “error”;
mod = false;
}
else
o1 = s.pop();
if (s.isempty())
mod = false;
else
{
o2 = s.pop();
mod = true;
}
}
void ope(char op)//連續將兩個操作數彈出并放在o1和o2中 如果成功 執行運算并將結果壓入棧
{
double oo1, oo2;
bool result = gettwo()}//執行由操作符op指定的運算
public:
void run()
void clear()
};
總結