因为项目使用QVector,太慢了,听说QMap比QVector查找时快,所以写一个小程序试试;
从30000个数据中找5000个
程序运行截图如下:
QVector
QMap
一样的数据,找一样的数代码如下图:
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QVector>
#include <QMap>
namespace Ui {
class Widget;
}
typedef struct MyData{
MyData(QString num1,QString num2,QString num3){
m_num1=num1;
m_num2=num2;
m_num3=num3;
}
QString m_num1;
QString m_num2;
QString m_num3;
}MyData;
typedef struct VecData{
VecData(const qint64 num,const QString name){
m_num=num;
m_name=name;
}
qint64 m_num;
QString m_name;
QList<MyData*> m_list;
}VecData;
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void vectorBtnClicked();
void mapBtnClicked();
private:
Ui::Widget *ui;
QVector<VecData*> m_myVec;
QMap<qint64,VecData*> m_myMap;
qint64 m_num[5000];
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <time.h>
#include <QMessageBox>
#include <QTimer>
#include <QTime>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->setWindowTitle("CSDN IT1995");
qint64 data=100000000;
for(qint64 i=0;i<30000;i++){
m_myVec.append(new VecData(data,"这个是name"));
m_myMap.insert(data,new VecData(data,"这个是name"));
for(int j=0;j<100;j++){
m_myVec[i]->m_list.append(new MyData("10000","20000","30000"));
(*m_myMap.find(data))->m_list.append(new MyData("10000","20000","30000"));
}
data++;
}
qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
for(int i=0;i<5000;i++){
m_num[i]=qrand()%100000+100000000;
}
connect(ui->vectorPushButton,&QPushButton::clicked,this,&Widget::vectorBtnClicked);
connect(ui->mapPushButton,&QPushButton::clicked,this,&Widget::mapBtnClicked);
}
Widget::~Widget()
{
delete ui;
}
void Widget::vectorBtnClicked(){
clock_t start,finish;
double totaltime;
start=clock();
for(int i=0;i<5000;i++){
for(int j=0;j<m_myVec.size();j++){
if(m_num[i]==m_myVec[j]->m_num){
qDebug()<<"Value:"<<m_myVec[j]->m_num;
break;
}
}
}
finish=clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
qDebug()<<"此程序的运行时间为"<<totaltime<<"秒!";
QMessageBox::information(this,"提示","使用了"+QString::number(totaltime,'f',5)+"秒");
}
void Widget::mapBtnClicked(){
clock_t start,finish;
double totaltime;
start=clock();
for(int i=0;i<5000;i++){
qDebug()<<"Value:"<<(*m_myMap.find(m_num[i]))->m_num;
}
finish=clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
qDebug()<<"
此程序的运行时间为"<<totaltime<<"秒!";
QMessageBox::information(this,"提示","使用了"+QString::number(totaltime,'f',5)+"秒");
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
---------------------
作者:草莓蛋糕人
来源:CSDN
原文:https://blog.csdn.net/u014746838/article/details/83504246
版权声明:本文为博主原创文章,转载请附上博文链接!