是否可以将现有结构设为数组?
struct violation v1={"AA1", "Defective_Brakes", 150};
struct violation v2={"AA2", "Disregarding_Traffic_Signs", 150};
struct violation v3={"AA3", "Driving_Under_the_Influence_of_Liquor", 2000};
struct violation v4={"AA4", "Driving_while_using_Mobile_Devices", 200};
struct violation v5={"AA5", "Drinving_without_License", 750};
struct violation v6={"AA6", "Driving_Against_Traffic", 2000};
struct violation v7={"AA7", "Failure_to_use_Seatbelt", 500};
struct violation v8={"AA8", "Illegal_Parking", 200};
struct violation v9={"AA9", "Overspeeding", 1200};
struct violation v10={"AA10", "Reckless_Driving", 750};
这应该是我的代码的数据库。我想把它变成一个数组,使数据库中的搜索更容易。我该怎么办?
答案 0 :(得分:0)
数组是同源的,即它只能保存一次,就像数组中的所有元素都是整数或字符串一样,但你不能混合你可以使用结构的类型,我在你的例子中看到你同时拥有String和Integer因此,如果您想将结构更改为数组,则必须将它们全部转换为字符串。
另外考虑你的情况,我会建议你继续使用结构,因为它混合了数据类型。您还可以使用struct violation violations [n];
将所有这些结构存储在一个数组中,然后使用for循环来填充违规行为,请按照How do you make an array of structs in C?获取完整示例。
答案 1 :(得分:0)
是。就像您对常规数组所做的那样,您可以创建一个struct
s:
struct violation v[10]={
{"AA1", "Defective_Brakes", 150},
{"AA2", "Disregarding_Traffic_Signs", 150},
{"AA3", "Driving_Under_the_Influence_of_Liquor", 2000},
{"AA4", "Driving_while_using_Mobile_Devices", 200},
{"AA5", "Drinving_without_License", 750},
{"AA6", "Driving_Against_Traffic", 2000},
{"AA7", "Failure_to_use_Seatbelt", 500},
{"AA8", "Illegal_Parking", 200},
{"AA9", "Overspeeding", 1200},
{"AA10", "Reckless_Driving", 750},
};
答案 2 :(得分:0)
您可以轻松地将数据放入数组中,而不是十个单独的变量:
struct violation violations[] = {
{"AA1", "Defective_Brakes", 150},
{"AA2", "Disregarding_Traffic_Signs", 150},
{"AA3", "Driving_Under_the_Influence_of_Liquor", 2000},
{"AA4", "Driving_while_using_Mobile_Devices", 200},
{"AA5", "Drinving_without_License", 750},
{"AA6", "Driving_Against_Traffic", 2000},
{"AA7", "Failure_to_use_Seatbelt", 500},
{"AA8", "Illegal_Parking", 200},
{"AA9", "Overspeeding", 1200},
{"AA10", "Reckless_Driving", 750}
};