简体   繁体   English

在 hash 表中找到最大值,然后打印具有该值的所有变量(在 C 中)

[英]find the maximum value in a hash table and then printing all the variables with that value (in C)

Having a struct like this:有这样的结构:

typedef struct person {
    char *name;
    int age;
} person

I insert each person I create in a hash table and what I want to do is find the oldest people, like this:我将我创建的每个人插入到 hash 表中,我想做的是找到最年长的人,如下所示:

Oldest People:
Austin 29
John 29
Matthew 29

I was wondering if there was a more efficent way to find the maximum age than searching the hash table twice: one to find the maximum value and the other to print all the people with the max value.我想知道是否有比搜索 hash 表两次更有效的方法来找到最大年龄:一次找到最大值,另一个打印所有具有最大值的人。

You can determine the maximum age while inserting.您可以在插入时确定最大年龄。 You need that if-clause anyways, but this way you save walking over the hash table for that.无论如何你都需要那个 if 子句,但这样你就可以省去 hash 表的麻烦。

Apart from that, you didn't say what is the key of your hash table.除此之外,您没有说 hash 表的密钥是什么。 I assume, it is the name, since you didn't mention resolving age collisions and you mentioned the need for a second pass.我想,这是名字,因为你没有提到解决年龄冲突,你提到需要第二次通过。

And I guess the purpose of your hash table is not just solving this problem.而且我猜您的 hash 表的目的不仅仅是解决这个问题。 But if it was, I wouldn't use a hash table but just keep a list of the names with the current maximum age and reset it as soon as the maximum age changes.但如果是这样,我不会使用 hash 表,而只是保留当前最大年龄的名称列表,并在最大年龄更改后立即重置它。 The list could be implemented as an array + size variable in case you know the maximum size, otherwise eg with a linked list of fixed size blocks.如果您知道最大大小,则可以将列表实现为数组 + 大小变量,否则例如使用固定大小块的链表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM