【发布时间】:2020-08-31 04:57:48
【问题描述】:
我目前有一个函数可以执行问题所说的(计算字符串中每个单词的出现次数)但是它使用 map。这是针对大学级别的任务,我们不允许使用地图进行计数(我没看过哈哈)
void wordCount(std::string wordFile)
{
std::map<std::string, int> M;
std::string word = "";
for (int i = 0; i < str.size(); i++)
{
if (str[i] == ' ')
{
if (M.find(word) == M.end())
{
M.insert(make_pair(word, 1));
word = "";
}
else
{
M[word]++;
word = "";
}
}
else
word += str[i];
}
if (M.find(word) == M.end())
M.insert(make_pair(word, 1));
else
M[word]++;
for (auto &it : M)
{
std::cout << it.first << ": Occurs "
<< it.second
<< std::endl;
}
}
所以我的问题是,有没有办法做上述但使用数组而不是映射?
【问题讨论】:
-
当然,要计数的单词映射只是两个数组:在数组中搜索单词,然后在找到它的位置获取索引,并在计数数组上使用该索引。
-
请注意,您的基于
map的解决方案效率非常低且不必要地复杂。可以大大简化:void wordCount(const std::string &wordFile) { std::map<std::string, int> M; std::istringstream iss(wordFile); std::string word; while (iss >> word) { M[word]++; } for (const auto &it : M) { std::cout << it.first << ": Occurs " << it.second << std::endl; } } -
This is for a university level task and we arent allowed to use maps for the count。我把它读成This is for a university level task and we arent allowed to use screwdrivers to loosen the screws
标签: c++ arrays dictionary count