sort()使用<的问题为了我的课

时间:2017-11-21 13:26:05

标签: c++ sorting

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

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

我没有编译错误。我已经测试了我的类的运算符<(),它在比较Person类的两个对象时起作用。但是,Person对象向量的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

1 个答案:

答案 0 :(得分:1)

更改您的赋值运算符,如下所示:

// 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检查,过早返回,而在其他路径上没有返回路径(最后)。

你的比较运算符已经由@StoryTeller指出:

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

您还可以制作比较运算符const,使用std::string等。