lundi 5 avril 2021

I try to take a random word from a vector but it takes the same words everytime [duplicate]

As I mentioned on the title; I have a vector which stores a bunch of words(around 2000 words) and in a part of the project it's expected from me that take a random word from that vector and display it. (the project is word finding-like) I have two classes that one of is main, and other is for taking word from vector. I attached the codes below. Something must have escaped my notice, but I can't get what it is somehow.

#include <iostream>
#include <vector>//must be
#include <string>//must be
#include "Dictionary.h"
#include <set>
using namespace std;

int main()                               //main
{
   vector<string> words;
   Dictionary dict(words);
   words = dict.setElements();
   string randomWord = dict.getaRandomWord(words);   //this line is for generate a random word
   cout << randomWord;         

   return 0;
}

class Dictionary                        //dictionary class
{
public:

Dictionary(::vector<string> a) {
    //getWordsFromFile() = a;
}


/*  public :vector<string> getWordsFromFile() {
vector<string> words;
ifstream inFile;
string tmp;
inFile.open("words.txt");
while (!inFile.eof()) {
    inFile >> tmp;
    words.push_back(tmp);
}

return words;


}*/

vector<string> setElements() {
// Declaring Vector of String type 
set<string> wordsSet;
string buffer;
vector<string> wordsVector;
ifstream inFile;
string tmp;
inFile.open("words.txt");

while (!inFile.eof()) {
    inFile >> buffer;
    wordsSet.insert(buffer);
}

for (set<string>::iterator it = wordsSet.begin(); it != wordsSet.end(); ++it) {
    wordsVector.push_back(*it);
}


/*for (int i = 0; i < wordsVector.size(); i++) {
    cout << wordsVector.at(i)<<endl;            //its for displaying the elements of the vector
}*/

return wordsVector;


}

string getaRandomWord(vector<string> a) {           //function that has supposed to be generate a random word
    
    vector<string> currentVector = a;
    string randomWord;
    int randomNumber = rand() % currentVector.size();
    randomWord = currentVector.at(randomNumber);
    return randomWord;
}
};

takes aging ever

takes aging everytime




Aucun commentaire:

Enregistrer un commentaire