VectorSearch/QVectorSearch/mainwindow.cpp

96 lines
2.5 KiB
C++

#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "finder.h"
#include "linear_finder.h"
#include "parallel_finder.h"
#include "timer.h"
#include "word_list_generator.h"
#include <thread>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
ui->resultView->setModel(&result_model_);
ui->searchAlgorithmSelector->setModel(&search_algorithms_);
setupAlgorithmSelector();
generateWordList();
}
MainWindow::~MainWindow() { delete ui; }
void MainWindow::setupAlgorithmSelector() {
search_algorithms_.appendRow(new QStandardItem("Linear search"));
search_algorithms_.appendRow(new QStandardItem("Parallel search"));
}
void MainWindow::generateWordList() {
Timer timer;
word_list_ = WordListGenerator().generate();
timer.stop();
std::stringstream status_message;
status_message << "generated " << word_list_.size() << " words in " << timer;
ui->mainStatusBar->showMessage(QString::fromStdString(status_message.str()));
QStringList words;
for (auto word : word_list_) {
words.append(QString::fromStdString(word));
}
result_model_.setStringList(words);
}
void MainWindow::search(const QString &search_term) {
if (search_term.isEmpty()) {
result_model_.setStringList(QStringList());
ui->mainStatusBar->clearMessage();
return;
}
Timer timer;
const auto finder = createSelectedFinder();
const auto results = finder->find_prefix(search_term.toStdString());
timer.stop();
std::stringstream status_message;
status_message << "search took " << timer << ", found " << results.size()
<< " results";
ui->mainStatusBar->showMessage(QString::fromStdString(status_message.str()));
showResults(results);
}
std::unique_ptr<Finder> MainWindow::createSelectedFinder() const {
auto selectedFinder = ui->searchAlgorithmSelector->currentIndex();
switch (selectedFinder) {
case 0:
default:
return std::make_unique<LinearFinder>(word_list_);
case 1:
return std::make_unique<ParallelFinder>(
word_list_, std::thread::hardware_concurrency());
}
}
void MainWindow::showResults(const std::vector<const std::string *> &results) {
QStringList ui_results;
for (auto word : results) {
ui_results.append(QString::fromStdString(*word));
}
result_model_.setStringList(ui_results);
}
void MainWindow::on_searchInput_textChanged(const QString &search_term) {
search(search_term);
}
void MainWindow::on_searchAlgorithmSelector_currentIndexChanged(int) {
search(ui->searchInput->displayText());
}