【发布时间】:2017-01-31 21:01:33
【问题描述】:
您好,我在使用此代码时遇到了一些问题。
【问题讨论】:
-
为什么不简单地使用
std::unordered_map<std::string, int>将单词映射到其频率?
您好,我在使用此代码时遇到了一些问题。
【问题讨论】:
std::unordered_map<std::string, int> 将单词映射到其频率?
计算唯一词的最佳方法是使用std::unordered_map<std::string, int>,然后在映射中递增值:wordMap[word]++; 请注意,如果这是单词的第一次出现,将创建默认值,它是 0,即非常适合这项任务。
除此之外,当有 std::sort 时,最好自己实现排序,这在大多数情况下都很好。
【讨论】:
冒泡排序:
vector<string> strings = split(str);
for (int i = 0; i < strings.size(); i++) {
for (int j = 0; j < strings.size() - 1; j++) {
if (strings[j + 1] < strings[j]) {
string tmp = strings[j];
strings[j] = strings[j + 1];
strings[j + 1] = tmp;
}
}
}
点餐后数词:
string prev = strings[0];
int counter = 1;
for (int i = 1; i < strings.size(); i++) {
if (strings[i] == prev) {
counter++;
} else {
cout << prev << ": " << counter << " ";
prev = strings[i];
counter = 1;
}
}
【讨论】:
您可以使用 std::find from algorithm:
std::find(strings.begin(), strings.end(), the_word_you_looking_for) != strings.end()
这会返回一个 bool(如果存在则为 true,否则为 false)。
您还可以设置一个计数器,然后在遇到每个true 时将其递增。
【讨论】:
这样做的一种方法是将所有子字符串保存到向量中,然后在向量上使用 std::count 函数并将结果放入映射中。这是示例代码
std::string s = "This is very good text and is really good to read";
// Putting all substrings into a vector.. Need code to do that, for simplicity I am showing here manually
vector<string> v1;
v1.push_back("This");
v1.push_back("is");
v1.push_back("very");
v1.push_back("good");
v1.push_back("text");
v1.push_back("and");
v1.push_back("is");
v1.push_back("rally");
v1.push_back("good");
v1.push_back("to");
v1.push_back("read");
// Map to create the result
map<string, int> mp;
for (auto v : v1) {
size_t n = std::count(v1.begin(), v1.end(), v);
mp[v] = n;
}
for (auto mvalue : mp) {
cout << "String = " << mvalue.first.c_str() << " Count Is " << mvalue.second << endl;
}
【讨论】: