在std :: vector上的std :: sort比较但从不替换

时间:2011-03-23 15:21:57

标签: c++

排序后数组保持不变。怎么可能?我可以看到健康的比较结果。

有一个拥有std :: vector的模型类:

private:
     std::vector<Contact> contacts;

班级联系人:

  1. QString私人会员
  2. QString私有成员getter - GetName()
  3. 处理成员的复制构造函数
  4. 处理成员的作业运算符
  5. &LT;运算符定义如下:

  6. bool Contact::operator < (const Contact& contact) const {
        QString str1 = contact.GetName();
        QString str2 = this->GetName();
        bool b = (QString::compare(str1,str2) < 0);
        return b;
    }
    

    我在排序期间调试此方法,并且每次都发现返回正确的“b”。正确检索名称,进行正确比较,“b”返回代码始终正确。

    在拥有向量的类中,我有一个排序方法......

    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());
        }
    }
    

4 个答案:

答案 0 :(得分:1)

矢量已经排序!!

答案 1 :(得分:1)

我发现了问题。

我在矢量中存储的类的赋值运算符有问题。

我的赋值运算符没有返回一个健康的“* this”,而是声明了一个新对象,用rhs数据初始化它并返回它。

所以效果就像我描述的那样。正确比较,但由于此错误没有“交换”。

答案 2 :(得分:0)

刚开始:

  1. 您的比较仿函数(或运算符&lt;,或更少)可能不正确。

  2. 您可以传递错误的迭代器对(v.begin,v.begin())。

  3. 可能已经排序了。

答案 3 :(得分:0)

  

数组在排序后保持不变。

什么阵列?你是从数组初始化一个向量?在这种情况下,向量具有自己的数据副本,对向量进行排序对数组没有影响。例如:

int array[] = {5, 2, 7, 3};
std::vector<int> vec(array + 0, array + 4);
std::sort(vec.begin(), vec.end());

现在向量将包含数字{2, 3, 5, 7},但数组将保持不变。如果要对数组本身进行排序,请执行以下操作:

int array[] = {5, 2, 7, 3};
std::sort(array + 0, array + 4);