[英]Bubble Sorting a string in an Array
I am trying to bubble sort the LastName property (under a struct StudentRecord, hence the names) of an array using bubble sort. 我试图使用冒泡排序冒泡排序数组的LastName属性(在结构StudentRecord下,因此名称)。 But I am having trouble doing so.
但我这样做有困难。
I am receiving the error (I'm using MinGW to compile): 我收到错误(我正在使用MinGW编译):
Invalid array assignment
Here is my code: 这是我的代码:
void option2 (StudentRecord student[], int n)
{
int pass = 1;
bool done = false;
StudentRecord temp;
while (!done && pass <= n-1)
{
done = true;
for (int i = n-1; i >= pass; i--)
{
if (student[i].lastName < student[i-1].lastName)
{
temp.lastName = student[i].lastName;
student[i].lastName = student[i-1].lastName;
student[i-1].lastName = temp.lastName;
done = false;
}
}
pass++;
}
}
It looks like lastName
is an array of characters. 看起来
lastName
是一个字符数组。
You can't assign entire arrays to each other; 您不能相互分配整个数组; you need to use
strcpy()
(#include <cstring>
) to copy one to the other. 你需要使用
strcpy()
(#include <cstring>
)将一个复制到另一个。 Additionally, using <
with character arrays will cause the memory addresses of the first elements in each array to be compared, not the entire string of characters; 另外,使用
<
with character arrays会导致比较每个数组中第一个元素的内存地址,而不是整个字符串; use strcmp
for this (which returns < 0 iff the first parameter is lexicographically < the second parameter). 使用
strcmp
(如果第一个参数按字典顺序<第二个参数,则返回<0)。
Note you can (and probably should) use std::string
instead (#include <string>
), which will automatically provide copying, comparison, and dynamic growth for you transparently. 请注意,您可以(并且可能应该)使用
std::string
(#include <string>
),这将自动为您提供透明的复制,比较和动态增长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.