【QT】实例三--移植容器排序程序

功能要求

输入要排序的元素数量(最好大一点),返回其排序时间。

在这里插入图片描述

建立Qwidget

UI设计如下
在这里插入图片描述

需移植的代码

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
class Sort_v
{
private:
	vector<int>a;
	vector<int>::iterator p;
	int n;
public:
	Sort_v(int nn)
	{
		n=nn;
		srand(time(0));
		for(int i=0;i<n;++i)
		{
			a.push_back(rand()%n);
		}
	}
	void browse()
	{
		for(p=a.begin();p!=a.end();++p)
			{
				cout<<*p<<endl;			
			}
	}
	int sort_v()
	 {
	 	clock_t t1,t2;
	 	t1=clock();
	 	sort(a.begin(),a.end());
	 	t2=clock();
	 	return t2-t1;
	 }
};
int main()
{
	Sort_v t(100000);
	t.sort_v();
	return 0;
}

进入到头文件,拷贝程序用到的头文件

在头文件里,放置自己的类,函数内容去掉,只留函数声明
而在cpp文件中,只留下函数内容,每个函数前加类的名称。
在这里插入图片描述类也拷贝过来,只留函数声明,记得函数后的

class Sort_v
{
private:
	vector<int>a;
	vector<int>::iterator p;
	int n;
public:
	Sort_v(int nn);
	void browse();
	int sort_v();
};

在这里插入图片描述到cpp文件中补充函数内容,注意声明类下的函数,添加class::
在这里插入图片描述

Sort_v::Sort_v(int nn)
{
    n=nn;
    srand(time(0));
    for(int i=0;i<n;++i)
    {
        a.push_back(rand()%n);
    }
}
void Sort_v::browse()
{
    for(p=a.begin();p!=a.end();++p)
        {
            cout<<*p<<endl;			
        }
}
int Sort_v::sort_v()
 {
    clock_t t1,t2;
    t1=clock();
    sort(a.begin(),a.end());
    t2=clock();
    return t2-t1;
 }
然后对容器排序按钮设置槽函数:

在这里插入图片描述

void MainWindow::on_pushButton_clicked()
{
    QString s;//接受要排序的数字个数
    s=ui->lineEdit->text();
    int nn=s.toInt();//text内容转为数字int型
    Sort_v sort1(nn);//初始化一个nn大小的sort1对象
    QString t;//接受排序时间
    t.sprintf("%d",sort1.sort_v());
    ui->lineEdit_2->setText(t);
}

在这里插入图片描述

实现

在这里插入图片描述

posted @ 2021-04-23 00:57  flybird2008  阅读(13)  评论(0)    收藏  举报  来源