所以我打开了一个CSV文件,并将其添加到结构中。我现在想按结构的U值(从最低到最高)对结构进行排序。我所做的工作有些奏效,但它交换的是交换的值,例如x和y,但这些交换的值并不意味着要交换,但仍按U排序。 我的结构-
typedef struct {
float xvalue;
float yvalue;
float uvalue;
float vvalue;
} flow_data;
int num_compare(const void *v1, const void *v2)
{
const flow_data *p1 = (flow_data *)v1;
const flow_data *p2 = (flow_data *)v2;
if (p1->uvalue < p2->uvalue)
return -1;
else if (p1->uvalue > p2->uvalue)
return +1;
else
return 0;
}
我在哪里运行代码-
FILE* fp = fopen(flow_file, "r");
// Checking if the file has been read succesfully
if( fp == NULL)
{
perror("Error opening file");
exit(1);
}
char buf[500];
fgets(buf, sizeof(buf), fp); // Skip the first line
int total = 0;
flow_data d;
flow_data* dataset = NULL;
while(4 == fscanf(fp, "%f, %f, %f, %f\n", &d.xvalue, &d.yvalue, &d.uvalue, &d.vvalue))
{
dataset = realloc(dataset, sizeof(*dataset) * (total + 1));
dataset[total] = d;
total++;
}
qsort(dataset, total, sizeof(dataset), num_compare);
答案 0 :(得分:3)
更改
activate
收件人
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0-preview1-35029" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.0-preview1-35029" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.0-preview1-35029" />
<PackageReference Include="Microsoft.Extensions.Identity.Stores" Version="2.2.0-preview1-35029" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj" />
<ProjectReference Include="..\Database.Entities\Database.Entities.csproj" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference
Include="Microsoft.EntityFrameworkCore.Tools"
Version="2.0.0" />
<DotNetCliToolReference
Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore">
<HintPath>..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.identity.entityframeworkcore\2.0.3\lib\netstandard2.0\Microsoft.AspNetCore.Identity.EntityFrameworkCore.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
或
qsort(dataset, total, sizeof(dataset), num_compare);
因为指针的大小并不总是与结构的大小相同。