我试图解决 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/