如何在c++中用单词作为键填充一个映射

How to fill a map with words as key in C++

本文关键字:填充 映射 一个 c++ 单词作      更新时间:2023-10-16

情况如下:

我将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

我知道的方法是使用字符串操作将字符串分成一个单独的单词数组。

是否有其他有效的方法将字符串分割成单词数组并以单词作为键填充映射?

  1. 您需要将输入字符串拆分为子字符串。
  2. 查找输入字符串中每个子字符串的出现次数。
  3. 将子字符串存储为键,并将计数作为映射中的值。

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检查每个单词是否在映射中,并将其分配到映射中或更改其值的值