C++ Search Problems
The following code below takes an array of string items (tokens) and searches for the lexographically largest, well it should anyways. The problem is that the program seems to reach the base case just fine, hand back and do the first comparison than BOOM. The stack dumps. No warnings or anything. Any ideas on what is going wrong?
std::string& largestWord(std::string items[],int numberWords){
int middle = numberWords/2;
std::string& rightLWord = largestWord(items, middle+1,numberWords);
std::string& leftLWord = largestWord(items, 0, middle);
if(leftLWord >= rightLWord){
return leftLWord;
}
return rightLWord;
}
std::string& largestWord(std::string items[],int left,int right){
if(right == left){
return items[left];
}
int middle = ( (left+right)/2 );
std::string& leftLWord = largestWord(items,left,middle);
std::string& rightLWord = largestWord(items,middle+1,right);
if(leftLWord >= rightLWord){
return leftLWord;
}
return rightLWord;
}
[1124 byte] By [
zbobet2012] at [2007-11-20 11:46:38]

# 1 Re: C++ Search Problems
I can't quite follow what you are doing. It almost looks like you
are doing some type of binary search. But if they are already
sorted, you would just return the last element.
You can use std::max_element in <algorithm> to find the
largest element.