簡體   English   中英

我被困在如何使用 C++ 中一個人的名字和姓氏在雙向鏈表中進行排序算法

[英]I'm stuck on how to make a sorting algorithm in a doubly linked list using a person's first name and last name in C++

所以我制作了一個雙向鏈表,其中存儲了一個人的名字、姓氏、地址和年齡,而我目前正堅持為列表制作排序算法。 到目前為止,我已經設法創建了 3 個函數,一個將節點添加到列表中,一個從列表中刪除一個節點,一個用於打印列表。 這是我到目前為止所擁有的結構:

    struct Node {
    string First_Name;
    string Last_Name;
    string Address;
    int age;
    Node* next;
    Node* prev;
} *first = 0, * last = 0;

addToList function:

void addToList()
{
    string temp = "Yes";
    string First_Name;
    string Last_Name;
    string Address;
    int age;
    Node* current = first;

    while (temp == "Yes") {

        cout << "Enter the persons first name: ";
        cin >> First_Name;
        cout << "Enter the persons last name: ";
        cin >> Last_Name;
        cout << "Enter the persons age: ";
        cin >> age;
        cout << "Enter the persons address: ";
        cin >> Address;
        cout << "Would you like to add another person? Yes or No";
        cin >> temp;

        current = new Node;
        current->First_Name = First_Name;
        current->Last_Name = Last_Name;
        current->age = age;
        current->Address = Address;
        if (last) last->next = current;
        else first = current;
        current->prev = last;
        current->next = 0;
        last = current;
    }
    return;
}

和打印清單:

void printList()
{
    if (!first)
    {
        cout << "Nothing is present in the list." << endl;
        return;
    }
    Node* current = first;
    while (current)
    {
        cout << current->First_Name << " " << current->Last_Name << " " << current->age << " " << current->Address << endl;
        current = current->next;
    }
}

我的問題是,我如何才能按字母順序對列表進行排序,我以前從未進行過排序......謝謝!

要對雙向鏈表使用自定義排序,重載operator<

struct Person
{
  std::string first;
  std::string last;
  std::string address;
  unsigned int age;
  bool operator<(const Person& p) const
  {
      bool is_less_than = false;
      if (last == p.last)
      {
          is_less_than = first < p.first;
      }
      else
      {
          is_less_than = last < p.last;
      }
      return is_less_than;
  }
};

現在您可以使用std::list ,它會自動按姓氏排序,然后是第一個。 std::list是一個雙向鏈表。

要比較Person

  Person a;
  Person b;
  //...
  if (a < b)
  {
     std::cout << "Person A < Person B\n";
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM