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

注意,博客所有代码在VS上均能编译通过,codeblocks等编译器可能因为某些变量名无法识别而无法编译。(我的VS上不能用end做变量名就很迷呀)
/************************************************/
(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);
    }
}
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值