您的位置:首页 > 编程语言 > C语言/C++

DLUT C++上机作业(实验七)

2017-04-18 19:00 190 查看
注意,博客所有代码在VS上均能编译通过,codeblocks等编译器可能因为某些变量名无法识别而无法编译。(我的VS上不能用end做变量名就很迷呀)

/[b]************************************************[/b]/

(1)用函数模板方式设计一个函数模板sort,采用直接插入排序方式对数据进行排序,并对整数序列和字符序列进行排序。

template < class T>

void sort(T a[], int n)

#include<iostream>
using namespace std;
template<class T>
void Sort(T a[], int n)
{
int i;
T temp;
for (i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
temp = a[i];
while (temp < a[i - 1] && i >= 1)
{
a[i] = a[i - 1];
i--;
}
a[i] = temp;
}
}
}
int main(){
int arr[4] = { 3, 2, 1, 5 };
Sort(arr, 4);
for (int i = 0; i < 4; i++)cout << arr[i] << " ";
char s[5] = "dfgd";
Sort(s, 4);
cout << s << endl;
}


(2)用类模板方式设计一个栈类stack,其中有两个私有数据成员:s[](存放栈元素)和top(栈顶元素下标),以及3个公有成员函数:push(元素入栈)、pop(元素出栈)和stackempty(判断栈是否为空),并建立一个整数栈和一个字符栈。

#include<iostream>
using namespace std;
template<class T>
class stack{
private:
T s[20];
int top;
public:
void push(T);
void pop(T&);
int stackempty();
stack();
};
template<class T>
stack<T>::stack(){
top = -1;
}
template<class T>
void stack<T>::push(T x){
if (top == 19){
cout << "mistake" << endl;
}
else{
s[++top] = x;
}
}
template<class T>
void stack<T>::pop(T&x){
x = s[top--];
}
template<class T>
int stack<T>::stackempty(){
if (top==-1)return 1;
return 0;
}
int main(){
stack<int> num;
stack<char>str;
if (num.stackempty())cout << "empty()" << endl;
else cout << "is not empty()" << endl;
for (int i = 0; i < 10; i++){
num.push(i);
}
if (num.stackempty())cout << "empty()" << endl;
else cout << "is not empty()" << endl;
int x;
num.pop(x);
cout << x << endl;
for (int i = 0; i < 10; i++){
str.push('a' + i);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  作业