C++ Maps 和 Sets 相关查询

标签 c++ maps set containers

我试图解决 c++ 入门书中关于 map 和集合的一个特定问题,我必须在其中制作一个用作单词计数器的 map 容器,但我必须忽略标点符号和大小写。例如,“例子”。 “example”和“Example”都应该在单词计数器中递增相同的键。

map 的基本代码如下:-

map<string, size_t> word_count;
string word;

while (cin >> word)
    ++word_count[word];

for (const auto &a : word_count)
    cout <<a.first<<" occurs "<<a.second<<((a.second>1) ? " times" : " time");

那么我应该在这段代码中添加什么,以便我的单词计数器忽略相同单词的大小写和标点符号?

最佳答案

#include <map>
#include <cstdlib>
#include <iostream>
#include <algorithm>

using std::map;
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::getline;
using std::transform;
using std::remove_if;

int main( int, char** )
{
    map< string, string::size_type > dictionary;

    string word = "";

    while ( getline( cin, word ) )
    {
        word.erase( remove_if( word.begin( ), word.end( ), ::isspace ), word.end( ) );
        word.erase( remove_if( word.begin( ), word.end( ), ::ispunct ), word.end( ) );

        transform( word.begin( ), word.end( ), word.begin( ), ::tolower );

        dictionary[ word ]++;
    }

    for ( const auto& entry : dictionary )
    {
        auto word = entry.first;
        auto count = entry.second;

        cout << "'" << word << "' total count: " << count << endl;
    }

  return EXIT_SUCCESS;  
}

构建

clang++ -stdlib=libc++ -std=c++11 -o homework homework.cpp

资源

关于C++ Maps 和 Sets 相关查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20857267/

相关文章:

c++ - Linux 中的 COM 端口检测

c++ - 维护 std::priority_queue 的堆属性

c++ - '\0' 是什么意思?

android - 如何在android中为 map 标记提供标签

python - 如何在 Python 中过滤集合中的文本

algorithm - 收集一组项目的优化算法

c++ - 如果它有主体,在抽象构造函数/析构函数中调用纯虚函数是否安全?

java - Android - 在 map 中仅显示确定区域中包含的标记

math - 如何将纬度/经度映射到扭曲的 map ?

java - 从数组中删除重复项。打印 HashMap 时出错