如何在txt文件中获取随机字符串c ++ ifstream? 有更好的解决方案吗?

问题描述

例如,我有带单词列表的txt db(在屏幕上),我需要在ifstream C ++中的此文件输出随机的3行。我在for循环中尝试过,但这非常有用

#include "gamewindow.h"
#include "ui_gamewindow.h"
#include <iostream>
#include <fstream>
#include <string>
#include <QLabel>
#include <ctime>
using namespace std;
string login;
bool start_is_clicked=false;
GameWindow::GameWindow(QWidget *parent) :
    QMainWindow(parent),ui(new Ui::GameWindow)
{
    ui->setupUi(this);
    ifstream logined("last_login.txt");
    getline(logined,login);
    QString qstring_login = QString::fromLocal8Bit(login.c_str());
    ui->login_label->setText(qstring_login);
    logined.close();
}

GameWindow::~GameWindow()
{
    delete ui;
}
int countStringsWords(){
    string current;
    int count = 0;
    ifstream words("word_db.txt");
    do{
        getline(words,current);
        count++;
    }while(!words.eof());
    words.close();
    return count;
}
void getLabelText(){
    srand(time(NULL));
    ifstream words("word_db.txt");
    int start=rand()%countStringsWords();
    words.close();
    cout<<start<<endl;
}
void GameWindow::on_Start_stop_clicked()
{
    if(ui->Start_stop->text()=="START"){
        ui->Start_stop->setText("STOP");
        getLabelText();
    }
    else if(ui->Start_stop->text()=="STOP"){
        ui->Start_stop->setText("START");
    }
    else{
        cout<<"Button error"<<endl;
    }
}

工作区:

int countStringsWords(){
    string current;
    int count = 0;
    ifstream words("word_db.txt");
    do{
        getline(words,current);
        count++;
    }while(!words.eof());
    words.close();
    return count;
}
void getLabelText(){
    srand(time(NULL));
    ifstream words("word_db.txt");
    int start=rand()%countStringsWords();
    words.close();
}

解决方法

升级当前解决方案:

您可以做的是使用动态列表(向量)用文件填充向量,然后生成3个随机索引并返回这三个随机字符串的数组。如果文本文件的长度为n,则这将是O(n)的空间和时间复杂度。

有更好的解决方案吗?

如果您希望O(1)的时间和空间复杂度(不考虑设备上的文件存储),那么我建议将文件设置为XML文件,因为这将允许您以任何本地索引访问文件,这意味着不需要将整个文件加载到数组中,对于较大的文件,不建议这样做。

import numpy as np
dic = {1: {8,2},2: {3},5: {9,7},7: {8},3: {8,4},4: {5},8: {9},9: {7}}
arr = np.zeros((9,9))
for k in dic.keys():
    for v in dic[k]:
        arr[k-1][v-1] = 1
print(arr)
,

添加到ZanyCactus的答案中。

如果您需要每个答案都唯一且可以使用C ++ 17,则可以使用std::sample

std::vector<std::string> random_words;
constexpr size_t number_of_random_words = 3;
std::sample(
    WordsFromFile.begin(),WordsFromFile.end(),std::back_inserter(random_words),number_of_random_words,std::default_random_engine(std::random_device()())
);