tags:

views:

279

answers:

2

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.

+1  A: 

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.

Alex
A: 

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.

Tim