【发布时间】:2021-02-27 03:03:33
【问题描述】:
所以我在一个文件中有一些单词。我将它们读到一个列表中,然后我试图找到每个单词的频率。我的问题是我必须遵循某个不太灵活的列表实现。 这是 List 类:
const int maxListSize = 50;
template<class T>
class List {
private:
int numberOfElements;
int currentPosition;
T data[maxListSize];
public:
List() {
numberOfElements = 0;
currentPosition = -1;
}
void insert(T element) {
if (numberOfElements >= maxListSize) {
cout << "List is Full" << endl;
return;
}
data[numberOfElements] = element;
numberOfElements++;
}
bool first(T &element) {
if (numberOfElements == 0) {
cout << "List is Empty" << endl;
return false;
}
else {
currentPosition = 0;
element = data[currentPosition];
return true;
}
}
bool next(T &element) {
//Check if the user called the first function
if (currentPosition < 0) {
cout << "Please call the first function before calling the next" << endl;
return false;
}
if (currentPosition >= numberOfElements - 1) {
//cout << "No next item" << endl;
return false;
}
currentPosition++;
element = data[currentPosition];
return true;
}
};
假设我的列表被称为名称。如何获取每个单词的频率?
【问题讨论】:
-
如果您可以仅使用给定的
List容器,那么您可以像List<std::pair<std::string, int>> names;那样制作一个配对列表,当您获得新单词,如果它已经在列表中,则将其关联的int值递增为计数器。