質問

I'm trying to create a linked list that is sorted by both name and rating. The rating sort part puts everything in the right order, but for some reason, the alphabetic sort doesn't put anything in the right order (or even in reverse order). Sometimes, the alphabet sort part of List::Insert breaks the printByRating() function. Will somebody please help?

Here is my insert function:

void List::insert(const Winery& winery)
{
    Node * prev = NULL;
    Node * curr = NULL;
    Node * newNode = new Node(winery);
    newNode->nextByName = NULL;
    newNode->nextByRating = NULL;

    //sort by name
    curr = headByName;

    while (curr!=NULL && curr->item.getName() < newNode->item.getName())
    {
        prev = curr;
        curr = curr->nextByName;
    }

    newNode->nextByName = curr;
    if(prev == NULL)
        headByName = newNode;
    else
        prev->nextByName = newNode;

    //sort by rating
    curr = headByRating;

    while (curr!=NULL && curr->item.getRating() > newNode->item.getRating())
    {
        prev = curr;
        curr = curr->nextByRating;
    }

    newNode->nextByRating = curr;
    if(prev == NULL)
        headByRating = newNode;
    else
        prev->nextByRating = newNode;
}

Here're the functions available to me in the Winery class:

const char * const getName() const { return name; }
const char * const getLocation() const { return location; }
const int getAcres() const { return acres; }
const int getRating() const { return rating; }
役に立ちましたか?

解決

It seems you are comparing const char* pointers instead of comparing their contents. Use strcmp or std::string to compare strings lexicographically.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top