首页 > 解决方案 > 如何更正这些 c++ 错误“无效转换”和“运算符不匹配”

问题描述

我正在尝试通读包含一系列单词和句子的文件。然后,需要存储唯一的单词并维护每个不同单词的计数。单词应按计数递减排序,如果有多个具有相同计数的单词,则按字母顺序排列。(这种排序可以在读入单词时实现,部分在读取单词时或在所有输入处理结束时实现。)最后,我想输出排序列表中的第一个和最后十个单词,以及他们的计数。

如何修复此const char*错误。我不知道我的代码有什么问题,也不知道我必须在哪里以及到底要更改什么:

[错误] 从 'char' 到 'const char*' 的无效转换 [-fpermissive]

[错误] 'operator<=' 不匹配(操作数类型为 'WordType' 和 'WordType')

struct WordType
{
    int word;
    int len, count;
};

const int MaxWords=50000;
char Words[MaxWords*10];
WordType Counters[MaxWords];
int NumWords=0;


bool Compare(WordType &A, WordType &B){
    if(A.count<B.count)return true;
    if(A.count>B.count)return false;
    char w1[50],w2[50];
    strncpy(w1,Words[A.word],A.len);   //Error comes here
    w1[A.len]='\0';
    w2[B.len]='\0';
    strncpy(w2,Words[A.word],B.len);   //Error comes here
    return strcmp(w1,w2) < 0 ;  
}

int partition (int low, int high)
{
    WordType pivot = Counters[high]; 
    int i = (low - 1); 

    for (int j = low; j <= high- 1; j++)
    {
        if (Compare(Counters[j] <= pivot))      //Error comes here
        {
            i++;
            swap(&Words[i], &Words[j]);
        }
    }
    swap(&Words[i + 1], &Words[high]);
    return (i + 1);
}

void quickSort(int low, int high)
{
    if (low < high)
    {
      int pi = partition(low, high);
       quickSort(low, pi - 1);
       quickSort(pi + 1, high);
    }
  }

标签: c++binary-search-tree

解决方案


(无论您对代码的意图是什么,我只查看了 3 个错误)

这个比较函数解决了第一个和第二个编译错误:

#include <string>

bool Compare(WordType &A, WordType &B)
{
    if (A.count < B.count)
        return true;

    if (A.count > B.count)
        return false;

    std::string w1{ Words[A.word] }, w2{ Words[B.word] }; // Fix

    return (strcmp(w1.c_str(), w2.c_str()) < 0);
}

compare 函数有 2 个参数,所以我猜你实际上想这样称呼它:

if (Compare(Counters[j], pivot)) // Fix

-

除此之外,我更喜欢使用std:array& 来初始化变量:

#include <array>

struct WordType
{
    int word = 0;
    int len = 0, count = 0;
};

constexpr int MaxWords = 50000;
std::array<char, MaxWords * 10> Words;
std::array<WordType, MaxWords> Counters;

int NumWords = 0;

// & to call in main():
Words.fill('\0');

推荐阅读