如何'Invalid conversion'和'no match for operator'更正这些 c++ 错误



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

如何修复此const char*错误。我不知道我的代码出了什么问题,也不知道我到底需要在哪里和什么地方改变:

[错误] 从"char">

到"const char*"的转换无效 [-允许]

[错误] 与"运算符<="不匹配(操作数类型为"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]='';
w2[B.len]='';
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);
}
}

(无论你对代码的意图如何,我只是看了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);
}

比较函数获得 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('');
if (Compare(Counters[j] , pivot))
strncpy(w2,(const char *)Words[A.word],B.len); 
strncpy(w2,(const char *)Words[A.word],B.len);  

这就是您的错误线应该是什么样子的

最新更新