开发者

strcmp struct in c - different elements

I have a struct member that holds lots of string elements. What I 开发者_如何转开发want is to iterate the whole member of the struct and count only different elements (diff last names).

struct log {
    char *last;
};
...
struct log *l
l->last = last_name; // loading *last member with data coming from last_name var
...

What would be a good way to compare and count unique elements currently on *last?

Any help will be appreciate it.


Sort your array on the last_name key. Duplicates will be next to each other.

Do a linear sweep through the array, checking how many entries after the current item have the same last name. Increment your counter once for all these duplicates. Increment your read-head to the first distinct entry.

For an array of size n: O(n lg n) + O(n) = O(n lg n) operations, assuming an O(n lg n) sort routine.


If you want to iterate over several items, it is a whole lot easier if these items are in an array. Could you consider redefining your struct definition to include the items in an array? You could perhaps index into the array using an enum or even a series of #defines.

If your data can't sensibly go into an array, you are likely to end up with a solution which looks like comparing the value with each item in the struct one at a time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜