【问题标题】:Linked list string sorting issue链表字符串排序问题
【发布时间】:2018-09-13 12:52:22
【问题描述】:

问题是如果我输入 1,然后输入 2 和 123。它将排序 1,123,2。
我如何让它排序 1,2,123

Item 是创建的记录。 Runner 是遍历器。

struct Records {
string Name;
string ID;
char Gender;
string Phone_Num;
Records *Next;
};

void SortRecords(Records* Item, Records* head, Records** Set_Head){
Records* Runner = head;

if (head == NULL){
    *Set_Head = Item;
}else if (Item->ID<head->ID){
    Item->Next=head;
}else{
    while(Item->ID>head->ID){
        if(Item->ID > Runner->ID && Runner->Next==NULL){
            Runner->Next=Item;
            break;
        }else if(Item->ID<Runner->Next->ID){
            Item->Next=Runner->Next;
            Runner->Next=Item;
            Runner=Item;
            cout<<Runner->Next->Name<<endl;
            break;
        }else{
            Runner=Runner->Next;
        }

    }

}

【问题讨论】:

  • 如果 string 真的是 std::string 那么你是在用 C++ 编程并且不应该使用 C 语言标签。
  • 这也解释了您遇到的排序问题,因为比较字符串时按字典顺序进行比较,其中任何字符串开始与例如'1' 将小于任何其他以 e.g. 开头的字符串'2'.
  • 将您的 ID 存储在 int 中或在进行比较时将其转换为 int。如果您不知道如何将字符串解析为整数,请查看如何。
  • 应用标签前请查看标签说明。 “c”标签明确告诉你什么时候可以和“c++”结合,什么时候不能。

标签: c++ string sorting linked-list


【解决方案1】:

您可以使用std::stoi 来比较整数而不是字符串:

std::stoi(Item->ID) < std::stoi(Runner->Next->ID)

您实际上可能希望将 ID 存储为整数,而不是字符串。

如果你的 ID 可以,比如“123AB”,那么你可以提取号码:

string str = "123AB";
size_t last_index = str.find_last_of("0123456789");
string result = str.substr(0, last_index + 1); // result = "123";

【讨论】:

    猜你喜欢
    • 2015-08-21
    • 1970-01-01
    • 2013-11-27
    • 2012-03-10
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多