c++ - 如何更正这些 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);
}
}
解决方案
(无论您对代码的意图是什么,我只查看了 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');
推荐阅读
- javascript - Javascript,如何将标签属性中的所有值放入数组中?
- c++ - 链接 GLFW 的本地安装
- javascript - JavaScript在数组中找到<=给定数字的第一个数字
- excel - 在 Internet Explorer 的组合框中选择值使用 excel vba
- javascript - 如何在不同的范围内使用 DOM 引用的 .value?(重构/范围问题)
- javascript - 如何在函数中调用javascript函数
- c++11 - 如何在 C++ 的初始化列表中正确缩进 emacs?
- python - 我怎样才能弄清楚这个 Python 代码是做什么的?
- r - 绘制多个光栅图像时填充空白
- javascript - 如何为 html 元素设置不同颜色(自动突出显示)的样式