c++ - 对结构进行合并排序不起作用

标签 c++ struct mergesort

我正在对结构执行合并排序。 排序是在目的地城市上进行的,它是一个数组 当我用普通数组尝试它时它起作用了。但它不适用于结构:(

#include <fstream>   // for std::ifstream
#include <sstream>   // for std::istringstream
#include <cstring>    // for std::string and std::getline
#include <iostream>
#include <ctype.h>
#include <stdio.h>
#include<algorithm>
#include <string.h>

using namespace std;

#define MAX 30
#define WORD 3


typedef struct node{
int nodeId;
char destCity[MAX];
char arrCity[MAX];
int time;
}NODE;

typedef struct edge{
 int adjoin;
int distance;
}EDGE;

typedef struct graph{
NODE cityNode[MAX];
EDGE e[MAX][MAX];
}GRAPH;

GRAPH graph,graphCpy,Temp;
GRAPH currentArray;


void MergeA(int low ,int mid , int high)
{
int i = low, j = mid+1 , k = low;

while(i <= mid && j <= high)
{
    if(currentArray.cityNode[i].destCity <= currentArray.cityNode[j].destCity)
    {
    strcpy(Temp.cityNode[k].destCity,currentArray.cityNode[i].destCity);
            i++;
    }
    else
    {
            strcpy(Temp.cityNode[k].destCity,currentArray.cityNode[j].destCity);
        Temp[k].assign(currentArray[j]);
            j++;
    }
    k++;
}
if(i > mid )
{
    for(int h = j ;h <= high ; h++ )
    {

    strcpy(Temp.cityNode[k].destCity,currentArray.cityNode[h].destCity);
        k++;

    }
}
else
    for(int h = i; h<= mid ; h++ )
    {

strcpy(Temp.cityNode[k].destCity,currentArray.cityNode[h].destCity);

    k++;

    }
 for(int i = low; i <= high ; i++){

    strcpy(currentArray.cityNode[i].destCity,Temp.cityNode[i].destCity);
}


}
void MergeSortA(int low , int high)
{

int mid = 0;
if(low < high)
{
    mid = low + (high-low)/2;
cout<<"beforemerge"<<endl;
    MergeSortA(low , mid);
    MergeSortA(mid+1,high);
    MergeA(low,mid,high);

}
}
int main(){
std::ifstream infile("theWords.txt");
    std::string line;
while (std::getline(infile,(line)) && count<30){
    std::istringstream iss(line);
            if ((iss) >>graph.cityNode[count].destCity >> graph.cityNode[count].arrCity  >> graph.cityNode[count].time){
graph.cityNode[count].nodeId = count ;
count++;
}
graphCpy= graph;
currentArray= graphCpy;
MergeSortA(0,count);
for(int i = 0; i <= count ; i++){
    cout << currentArray.cityNode[i].destCity <<endl;

    }
}

我将值输入到图形拷贝中,然后将其提供给 currentArray!!

最佳答案

您似乎认为可以使用 a < b 合理地比较字符数组.事实并非如此。你需要看看 strcmp()或者,最好使用 std::string而不是首先。就个人而言,我还强烈建议让合并排序算法完全独立于任何特定结构,并确保我可以合理地交换我的节点。

关于c++ - 对结构进行合并排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204204/

相关文章:

c++ - 我怎样才能访问双向链表中的嵌套结构?

C malloc() 与结构建议

java - 我的合并排序算法的输出未排序

c# - 如何从合并排序中获得O(n log(n))?

c++ - 具有可变高阶函数的重载分辨率

c++ - C++ 中的 set<pair> 和 map 有什么区别?

c++ - 无法使用 cmath 编译代码

c# - 在 pInvoke 中编码结构数组

ios - 扩展结构不是 Swift 的成员

algorithm - 归并排序计算复杂度时 "cn"到底是什么?