因此,我需要从input.txt文件中读取10,000个数字,然后搜索以查看它是否在数组中,如果不存在,则将其插入并在频率数组中递增频率值。然后,我需要按照频率数组的降序对数组进行排序。我知道我仍然想念很多...但是我的主要问题是在main.cpp中找到的。当我引用TermTable.BinarySearch和TermTable.Sort时,出现“错误:预期为标识符”。这是我的main.cpp文件。所以我最大的问题是:为什么我不能访问TermTable类中的方法?
#include <cstdlib>
#include <iostream>
#include <fstream>
#include "TermTable.h"
using namespace std;
int main(){
const int size = 10000;
int termArray[size];
int frequencyArray[size];
char * charArray = new char[size];
int position = 0;
ifstream fin("input.txt");
if (fin.is_open())
{
cout << "Open" << endl;
while (!fin.eof() && position < size){
fin.get(charArray[position]);
position++;
}
charArray[position - 1] = '\0';
for (int i = 0; charArray[i] != '\0'; i++)
{
termArray[i] = charArray[i];
}
for (int i = 0; termArray[i] != '\0'; i++){
int searchValue = termArray[i];
TermTable.BinarySearch(int termArray, int size, int searchValue);
if (position != -1){ frequencyArray[i] += 1; }
else if (position == -1){
frequencyArray[i] = 0;
}
}
TermTable.Sort(int termArray, int size);
}
else
{
cout << "couldn't open" << endl;
}
return 0;
}
这是我的规格.cpp文件。
#include <iostream>
#include <cstdlib>
#include "TermTable.h"
using namespace std;
int TermTable::BinarySearch(int array[], int size, int searchValue){
int first, last, middle, position; bool found; first = 0; last = size - 1; found = false; position = -1;
while (!found && first <=last)
{
middle = (first + last) / 2;
if (array[middle] == searchValue)
{
found = true;
position = middle;
}
else if (array[middle] > searchValue)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
void TermTable::Sort(int array[], int size){
int temp; bool swapOccurred;
do{
swapOccurred = false;
for (int count = (size-1); count > 0; count--)
{
if (array[count] < array[count - 1])
{
temp = array[count];
array[count] = array[count - 1];
array[count - 1] = temp;
swapOccurred = true;
}
}
} while (swapOccurred);
}
这是我的类(class)文件。
#include <cstdlib>
#include <iostream>
using namespace std;
//class specification
class TermTable {
public:
//constructor
TermTable();
//member functions
int BinarySearch(int array[],int size, int searchValue);
void Insert(int value);
void Sort(int array[],int size);
//destructor
~TermTable();
private:
//data
int currentAmount;
};
最佳答案
我发现了两件事:
BinarySearch()
和Sort()
是TermTable
类的成员函数,而不是静态方法。因此,您需要实例化TermTable
,然后使用该对象来调用这些方法。 在
main()
中:TermTable termTableObj;
termTableObj.BinarySearch(...);
...
termTableObj.Sort(...);
TermTable termTableObj;
termTableObj.BinarySearch(termArray, size, searchValue);
termTableObj.Sort(termArray, size);