c++ - 在我的类(class)中使用 < 的 sort() 问题

标签 c++ sorting

<分区>

我正在使用的代码来自 Ivor Horton 的“Beginning Visual C++ 2010”。 特别是 Ex10_02.cpp 使用 Person.h。

sort 函数对我的类对象不起作用。当输入姓名并最终按下 Enter 键时,姓名列表按照输入中给定的顺序输出,在调用 sort() 函数后,姓名再次输出到屏幕。它们应该根据第二个名字进行排序。但它们的输出顺序与我最初输入它们的顺序相同。

我没有得到任何编译错误。我已经为我的类测试了 operator<() ,它在比较 Person 类的两个对象时有效。但是,用于 Person 对象 vector 的 sort() 函数再次无法正常工作。我对为什么会这样没有更多的想法。欢迎任何见解。

代码如下:

// Ex10_02
// storing objects in a vector

#include <iostream>
#include <vector>
#include <algorithm>
#include "Person.h"

using namespace std;

int main()
{
    vector<Person> people;                 // Vector of Person objects
    const size_t maxlength(50);
    char firstname[maxlength];
    char secondname[maxlength];
    vector<int> numbers;

    // input all the people
    while(true)
    {
        cout << "Enter a first name or press Enter to end:";
        cin.getline(firstname, maxlength, '\n');
        if(strlen(firstname) == 0)
            break;
        cout << "Enter the second name: ";
        cin.getline(secondname, maxlength, '\n');
        people.push_back(Person(firstname, secondname));
    }

    // Output the contents of the vector
    cout << endl;
    auto iter(people.begin());
    while(iter != people.end())
        iter++->showPerson();

sort(people.begin(), people.end());
    cout << endl;
    for(auto i = 0; i < people.size(); i++)
   {
      people[i].showPerson();
   }

   cout << endl;
   for(auto i = 0; i < people.size(); i++)
   {
      people[i].showPerson();
   }
   cout << endl;
   cout << "Is people[0] < people[1] ?" << endl;
   if(people[0] < people[1])
   {
       cout << "YES" << endl;
       people[0].showPerson ();
       people[1].showPerson();
   }
   else
   {
       cout << "NO" << endl;
       people[1].showPerson();
       people[0].showPerson();
   }
   cout << endl;
   int myints[] = {32,71,12,45,26,80,53,33};
  vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33
   for(int i = 0; i < 8; i++)
    cout << myvector[i] << endl;
    cout << endl;
    // using default comparison (operator <):
    sort(myvector.begin(), myvector.end());           //(12 32 45 71)26 80 53 33
    for(int i = 0; i < 8; i++)
    cout << myvector.at(i) << endl;
    return 0;
}

//-----------------------------------------------------------------------

Person.h:

// A class defining people by their names
//#pragma once
#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED    
#include <cstring>
#include <iostream>
using namespace std;

class Person
{
public:
    // Constructor, includes no-arg constructor
    Person(const char* first = "John", const char*  second = "Doe")
    {
        initName(first, second);
    }
    // Copy constructor
    Person(const Person& p)
    {
        initName(p.firstname, p.secondname);
    }
    // Destructor
    ~Person()
    {
        delete[] firstname;
        delete[] secondname;
    }
    // Assignment operator
    Person& operator =(const Person& p)
    {
        // deal with p = p assignment situation
        if(&p == this)
        {
            return *this;

            delete[] firstname;
            delete[] secondname;
            initName(p.firstname, p.secondname);
            return *this;
        }
    }
        // Less-than operator
        bool operator <(const Person& p)
        {
            int result(strcmp(secondname, p.secondname));
            if(result < 0 || result == 0 && strcmp(firstname, p.firstname) < 0)
                return true;
            return false;
        }
        // output a person
        void showPerson() const
        {
            cout << firstname << " " << secondname << endl;
        }

private:
    char* firstname;
    char* secondname;

    // private helper function to avoid code duplication
    void initName(const char* first, const char* second)
    {
        size_t length(strlen(first)+1);
        firstname = new char[length];
        strcpy_s(firstname, length, first);
        length = strlen(second) + 1;
        secondname = new char[length];
        strcpy_s(secondname, length, second);
    }
};
#endif // PERSON_H_INCLUDED

最佳答案

像这样更改您的赋值运算符:

// Assignment operator
Person& operator =(const Person& p)
{
    // deal with p = p assignment situation
    if (&p != this)
    {

        delete[] firstname;
        delete[] secondname;
        initName(p.firstname, p.secondname);
    }

    return *this;
}

你有错误的&p == this 检查,返回太早,else 路径(最后)没有返回路径。

你的比较运算符就像@StoryTeller 已经指出的那样:

if (result < 0 || ( result == 0 && strcmp(firstname, p.firstname) < 0 ))

你也可以让你的比较运算符const,使用std::string

关于c++ - 在我的类(class)中使用 < 的 sort() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47414225/

相关文章:

java - 3 分区的中位数

Java 编译错误缺少 return 语句。需要澄清

c++ - 根据某些元数据在运行时转换参数包值

c - 希尔排序程序

c++ - 带有 GCC 和 clang 的 constexpr char 数组

c++ - 为什么作者声称此代码会导致种族歧视?

arrays - 在 Julia 中按多个键对 Dict 数组进行排序

c++ - std::bind 不适用于 std::sort

c++ - ./lib/gcc/x86_64-linux-gnu/4.6/libstdc++.a 的用法是什么

c++ - 两次读取文本文件中的一行