C++地图和集合相关查询

C++ Maps & Sets related queries

本文关键字:查询 集合 地图 C++      更新时间:2023-10-16

我试图解决c++入门书中关于地图的一个特定问题;在这些集合中,我必须制作一个用作单词计数器的地图容器,但我必须忽略标点符号&案例。例如,"example."、"example"answers"example"都应该增加单词计数器中的同一个键。

地图的基本代码如下:-

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家庭作业.cpp

资源

  • CPP参考网站
  • CPP资源网络
  • C++资源的最终列表

您可以使用tolower:

#include <algorithm>
#include <string> 
std::string str = "ExampleText"; 
std::transform(str.begin(), str.end(), str.begin(), ::tolower);

同时删除所有标点符号。为此,您必须使用自定义算法。