Simplification of code

I have the following function which determines whether there is a word in a set that begins with a certain string:


bool Dictionary::prefixExists(string prefix) const
{
	bool result = false;
	if(_words.lower_bound(prefix) != _words.end())
	{
		string lboundResult = *_words.lower_bound(prefix);
		if(lboundResult.size() >= prefix.size() && lboundResult[prefix.size() - 1] == prefix[prefix.size() - 1])
			result = true;
	}
	return result;
}

In order to avoid preforming the lower_bound() method twice, I would like to combine the functionality of the line:

if(_words.lower_bound(prefix) != _words.end())

with the line:

string lboundResult = *_words.lower_bound(prefix);

Does anyone know how this might be done?
I tried:

...
string lboundResult;
if((lboundResult = *_words.lower_bound(prefix)) != _words.end())
...

but that didn't work.
Last edited on
closed account (S6k9GNh0)
Why did that not work?
try:
1
2
3
4
5
6
string* lboundResult = _words.lower_bound(prefix);
if (lboundResult != _words.end())
{
    if (lboundResult->size() >= prefix.size() && (*lboundResult)[prefix.size() - 1] == prefix[prefix.size() - 1])
        result = false;
}
Thanks Stewbond! That's brilliantly simple. :)
If you really want to make it efficient, you could change it to:

1
2
3
4
bool Dictionary::prefixExists(string prefix) const
{
    return false ;
}


since it's incapable of returning true.

I ended up changing it a little like so:

        set<string>::iterator lboundResult = _words.lower_bound(prefix);
	if (lboundResult != _words.end())
	{
		if (lboundResult->size() >= prefix.size() && (*lboundResult)[prefix.size() - 1] == prefix[prefix.size() - 1])
			result = true;
	}

(The compiler didn't like the iterator to pointer conversion.)
Sorry, cire, I mis-typed.
It was supposed to be:

result = true;
Glad it helped.
Topic archived. No new replies allowed.