一些零碎程式碼

qq_41358574發表於2020-10-04

**

關於原始檔與標頭檔案:程式碼:標頭檔案程式碼

**:#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;
}

                }
                cout << endl;
            }
        }
}

關於將一個陣列移位:先寫一個函式向右移動一位,再寫一個函式呼叫前面的函式移動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++;//過濾空格;

len = 0;
while (*s1 != ' ' && *s1 != '\0')
{    
    *(temp + len) = *s1;//不能用*temp=*s1,why?
    len++;
    s1++;
}

*(temp + len) = '\0';//注意這種方式。
if (len > max)
{
    max = len;
    strcpy(s2, temp);
}

if (*s1 == '\0') break;

}}
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;

    }
    rudui(qu, 1);
    cout.width(4); cout << 1<<endl;
  
}
cout << endl;


}
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(int
table, 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++)

{
	for (vector<int>::iterator yj = (*mg).begin(); yj != (*mg).end(); yj++)
		cout << *yj;
	cout << endl;
}

}
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不同 則刪除陣列原有記憶體然後重新分配

	delete[]mm;//刪除陣列原有記憶體
	size = rhs.size;//設定本物件陣列大小
	mm = new T[size];//重新分配size個元素的記憶體
}

for (int i = 0; i < size; i++)
{
	mm[i] = rhs.mm[i];
}
return *this;//返回當前物件的引用

}
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;

for (i = 2; i < n; i++)
{//檢查i能否被比它小的質數整除
	bool judge = true;
	for (int j = 0; j < count; j++)//如果i被nice[j]整除說明i不是質數
	{
		if (i % nice[j] == 0)
		{
			judge = false;
			break;
		}
	}
	if (judge)
	{
		if (count == nice.getsize())//如果質數表滿了將其空間加倍
			nice.resize(count * 2);
		nice[count++] = i;
	}
}
for (i = 0; i < count; i++)
	cout <<setw(8)<< nice[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()
};

相關文章