如何在c++中用单词作为键填充一个映射
How to fill a map with words as key in C++
情况如下:
我将sting作为输入,使用如下:
string s;
getline (cin , s);
现在我想填充一个类型为<string, int>
的映射。该映射的键将是输入字符串中的单个单词。该值将存储单词的频率。
示例:输入字符串- " Hello My name is OP Hello World"
Map应该是这样的:
Hello - 2
My - 1
name - 1
= - 1
OP - 1
世界- 1
我知道的方法是使用字符串操作将字符串分成一个单独的单词数组。
是否有其他有效的方法将字符串分割成单词数组并以单词作为键填充映射?
- 您需要将输入字符串拆分为子字符串。
- 查找输入字符串中每个子字符串的出现次数。
- 将子字符串存储为键,并将计数作为映射中的值。
int main()
{
std::string input="Hello My name is OP Hello World";
std::map<std::string, int> myMap;
std::istringstream iss(input);
while (iss) {
std::string substr;
std::getline(iss,substr,' ');
int count = 0;
auto pos = input.find(substr, 0);
while (pos != std::string::npos) {
++count;
pos = input.find(substr, pos + 1);
}
if(substr.size() != 0)
myMap[substr] = count;
}
for (const auto &p : myMap) {
std::cout << p.first << "=" << p.second << 'n';
}
return 0;
}
Hello=2
My=1
OP=1
World=1
is=1
name=1
所以你说你有你的字符串分割,但你想找到一个更好的方法,所以这里是最优雅的方式在c++中分割字符串,假设你的单词是由空白空间分隔的。
现在你有了你的单词,得到你的单词并使用循环迭代它们,并在循环中使用以下命令:
WhateverYourMapName[WhateverTheCurrentWordIs]++;
此语句将使您现有的键 (word)的值增加1。或如果没有找到,它将添加一个新的键(word),初始值为1
。
如果您有一个基于分隔符将std::string
对象拆分为字符串数组的函数,那么您的任务实际上非常简单:
std::vector<std::string> lines;
std::string line;
while(std::getline(std::cin, line)) lines.emplace_back(line);
std::map<std::string, int> word_map;
for(const std::string & line : lines_of_input) {
//my_split_method can either be a standard library function, if one exists, or a function you've written yourself
std::vector<std::string> words = my_split_method(line);
for(const std::string & word : words) {
word_map[word]++;
}
}
for(const auto & word_pair : word_map) {
std::cout << "Frequency of "" << word_pair.first << "" is " << word_pair.second << std::endl;
}
使用strtok分割空格并迭代单词,通过find检查每个单词是否在映射中,并将其分配到映射中或更改其值的值
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在c++中用vector填充一个简单的动态数组
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 在循环(C++)中用新指针填充映射
- C++:通过从映射向量分配映射实例来填充映射的映射
- (VS2015)正在尝试用初始值设定项列表中的数据填充静态映射
- 在c++中填充和移除向量和映射中的元素
- 无法填充C数组的映射
- 如何填充映射的multimap
- 在函数中填充结构映射的最好方法是什么?
- 用c++在头文件中创建和填充映射
- 使用预先填充的对象映射实现工厂模式
- 创建一个编译时键到类型映射,该映射由对可变函数的调用填充
- 如何填充提升递归映射容器
- 如何在c++中用单词作为键填充一个映射
- 如何填充字符串和双精度向量对的映射