- #1
Jamin2112
- 986
- 12
So I've been making a class called Dictionary in C++. I just added a class function that tries to return the definition of a word by searching through a list of words in alphabetical order. The thing is, the word you're looking for might not be in there. Hence this should be a slightly modified version of the Bisection Method in math, because in that method you know there's a zero of the function.
Does this sound right?
Pseudo-code:
w = the word we're looking for
a = first word in dictionary
b = last word in dictionary
---while a ≠ b -----------------------
c = the word directly between a and b (Use integer division by 2 to find it)
if c > w, then a = c; otherwise, b = c
---------------------------------------
if a = w, then return the definition of a; otherwise, return an error message
Code:
word_val is a function that returns an unsigned integer. It's used to check whether one word is alphabetically greater or less than another, i.e. word_val(a) > word_val(b) iff a is alphabetically greater than b.
dict a private variable of my class, a vector of structures each of which contains a string for a word and another for the corresponding definition.
Does this sound right?
Pseudo-code:
w = the word we're looking for
a = first word in dictionary
b = last word in dictionary
---while a ≠ b -----------------------
c = the word directly between a and b (Use integer division by 2 to find it)
if c > w, then a = c; otherwise, b = c
---------------------------------------
if a = w, then return the definition of a; otherwise, return an error message
Code:
Code:
std::string Dictionary::getDef(std::string w) {
std::vector<Entry>::iterator a(dict.begin()), b(dict.end()), c;
while (a != b) {
c = a + (b - a)/2;
if (word_val(c->word) > word_val(w)) {
a = c;
} else {
b = c;
}
}
if (a->word == w) {
return (a->def);
} else {
return ("ERROR: Word not found.");
}
};
word_val is a function that returns an unsigned integer. It's used to check whether one word is alphabetically greater or less than another, i.e. word_val(a) > word_val(b) iff a is alphabetically greater than b.
dict a private variable of my class, a vector of structures each of which contains a string for a word and another for the corresponding definition.