I am trying to create a spell checker program. I load and sort a 480,000 word document into a vector. Now, I ask the user what word to spell check. I want to use a binary search to see if the word is in the dictionary. The problem is: I don't know how to use binary search for a vector. I have used it before with an array but can't seem to make it work with a vector. Here's my program:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
usingnamespace std;
int main(int argc, char *arg[] )
{
string wordToTest;
cout << "word to spell check?";
cin >>wordToTest;
//temp storage for each word
string word;
vector<string> dictionary;
//read the dictionary file
ifstream readFile("Words.txt");
//while there is a word, put it into the vector
while(getline(readFile, word, '\n'))
{
dictionary.push_back(word);
}
readFile.close();
sort(dictionary.begin(), dictionary.end());
//binary search here
return 0;
}
Now, I want to use this algorithm but make it work for a vector.
1 2 3 4 5 6 7 8 9 10 11 12 13
int binarySearch(int sortedArray[], int first, int last, int key) {
while (first <= last) {
int mid = (first + last) / 2; // compute mid point.
if (key > sortedArray[mid])
first = mid + 1; // repeat search in top half.
elseif (key < sortedArray[mid])
last = mid - 1; // repeat search in bottom half.
elsereturn mid; // found it. return position /////
}
return -(first + 1); // failed to find key
}
My first attempt was to change every array to vector but it didn't work. You don't have to write it for me just help me out, thanks!