std::sort on an std::vector compares but never replaces [closed]
the array stays the same after the sort. How is that possible? I can see the healthy comparison result.
There's a model class that owns a std::vector:
private:
std::vector<Contact> contacts;
The class contact has:
- QString private member
- QString private member getter - GetName()
- Copy constructor that handles the members
- Assignment operator that handles the members
- < operator defined as follows:
bool Contact::operator < (const Contact& contact) const {
QString str1 = contact.GetName();
QString str2 = this->GetName();
bool b = (QString::compare(str1,str2) < 0);
return b;
}
I am debugging this method during sort, and i find that the correct "b" is returned, every time. The names are retrieved correctly, are compared correctly, and the "b" return code is always correct.
In the class that owns the vector, I have a sort method...
void ContactsModel::sort ()
{
qDebug("Before Sorting: size: %d", this->contacts.size());
for (int i=0; i< this->contacts.size(); i++)
{
QString str = contacts[i].GetName();
qDebug(str.toAscii());
}
// trying to sort...
std::sort(this->contacts.begin(), this->contacts.end());
// PROBLEM: Output here is identical to what I had before the sort. The vector is not sorted, not even close. It's 52 random names in the same order they were initially put in the vector.
qDebug("After Sorting: size: %d", this->contacts.size());
for (int i=0; i< this->contacts.size(); i++)
{
QString str = contacts[i].GetName();
qDebug(str.toAscii());
}
}
The vector is already sorted!!
I found the problem.
My assignment operator on the class stored in the vector was faulty.
My assignment operator wasn't returning a healthy "*this", instead it declared a new object, initialized it with the rhs data and returned it.
so the effect was as I described. Correct comparison, but no "swapping" due to this error.
Just to start with:
Your comparison functor (or operator<, or less) could be incorrect.
You could pass incorrect pair of iterators (v.begin, v.begin()).
It could be already sorted.
the array stays the same after the sort.
What array? Are you initializing a vector from an array? In that case, the vector has its own copy of the data, and sorting the vector will have no influence on the array. Example:
int array[] = {5, 2, 7, 3};
std::vector<int> vec(array + 0, array + 4);
std::sort(vec.begin(), vec.end());
Now the vector will contain the numbers {2, 3, 5, 7}
, but the array will remain unchanged. If you want to sort the array itself, just do so:
int array[] = {5, 2, 7, 3};
std::sort(array + 0, array + 4);
精彩评论