1. 程式人生 > >QVector與QMap查找效率實戰(QMap快N倍)

QVector與QMap查找效率實戰(QMap快N倍)

運行時間 list int for string sta tps fin cst

因為項目使用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()<<"\n此程序的運行時間為"<<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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

QVector與QMap查找效率實戰(QMap快N倍)