Right now I have a class to do a binary search. The class accepts a vector, but then I tell the class to sort.
I need to be able to have it sort by only first name potentially or last name, so I set a character argument as a choice in that class to change how I sort the vector. I also in that class made an operator() function to use *this, as a class pointer to sort the vector. But it seems to just be looping forever. Can anyone tell me why? Code Below.
*note if there’s some general practices I’m not following feel free to inform me. I don’t want to start making bad habits now.
By request: Getname
void personType::getName(string& first, string& last)
{
// get the name and set it
first = firstName;
last = lastName;
}
bool sBinary::operator()(studentType student1, studentType student2){
string toCheck1, toCheck2, fName1,lName1 ,fName2 , lName2;
student1.getName(fName1, lName1);
student2.getName(fName2, lName2);
toCheck1=checkStr(fName1, lName1);
toCheck2=checkStr(fName2,lName2);
return toCheck1<toCheck2;
}
string sBinary::checkStr(string fName, string lName){
string toCheck;
switch (choice){
case 'f':
case 'F':
toCheck=fName;
break;
case 'l':
case 'L':
toCheck=lName;
break;
case 'r':
case 'R':
toCheck=fName+lName;
break;
default:
toCheck=lName+fName;
}
return toCheck;
}
sBinary::sBinary(vector<studentType> _sList, char _choice){
sList=_sList;
steps=0;
choice=_choice;
sort(sList.begin(),sList.end(), *this);
}
So, it seems not not to loop forever, but executes too long. It’s completely different story.
You have a couple of pessimisations in your code:
The main concern is that you pass
*this, to the sorting algorithm:std::sorttakes comparation predicate by value and it copies it many times. You can see it, if you define copy constructor:And your vector gets copied along with the object itself.
For example, if the array size is 200,
std::sortcopies object 13646 times. It means, that 2700000 student copy operations involved.So, you should not pass
*thistostd::sort. You’d better define static functionlessTheninstead ofoperator()and pass it to sorting algorithm.Further improvements:
Pass by reference, rather then by value. For example, in your
lessThenfunction declaration should look likeRefactor your
studentTypeclass.You’d better have 2 separate functions, returning first and last name (by constant reference). In this case you could get rid of copying names to temporary variables. Note, that when you have single function, you have to copy both first and last name, even if one name will never be used: