C 中的 strcmp 结构 - 不同元素
我有一个包含大量字符串元素的结构成员。我想要的是迭代结构的整个成员并仅计算不同的元素(不同的姓氏)。
struct log {
char *last;
};
...
struct log *l
l->last = last_name; // loading *last member with data coming from last_name var
...
比较和计算 *last 当前唯一元素的好方法是什么?
任何帮助将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
last_name
键对数组进行排序。重复项将彼此相邻。对数组进行线性扫描,检查当前项之后有多少条目具有相同的姓氏。对于所有这些重复项,将计数器增加一次。将您的阅读头增加到第一个不同的条目。
对于大小为
n
的数组:O(n lg n) + O(n) = O(n lg n)
运算,假设O(n lg n) n)
排序例程。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 anO(n lg n)
sort routine.如果您想迭代多个项目,那么如果这些项目位于数组中,就会容易得多。您是否可以考虑重新定义您的
struct
定义以包含数组中的项目?您也许可以使用enum
甚至一系列#define
来索引数组。如果您的数据无法明智地进入数组,那么您最终可能会得到一种解决方案,该解决方案看起来像是一次将值与结构中的每一项进行比较。
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 anenum
or even a series of#define
s.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.