我需要打印出十二个带有单词和频率(出现“单词”的次数)的文本文件,但这并不是要打印只出现一次的单词。我怎么不把那些话打印出来。我想知道如何基本能够使用向量的2nd值来做事。
#include <iostream>
#include <map>
#include <fstream>
#include <string>
#include<bits/stdc++.h>
#include <iterator>
using namespace std;
template <class KTy, class Ty>
void PrintMap(map<KTy, Ty> map)
{
typedef typename std::map<KTy, Ty>::iterator iterator;
std::vector<std::pair<std::string,int>> vector( map.begin(), map.end() );
std::sort( vector.begin(), vector.end(),
[]( const auto & lhs, const auto rhs )
{ return lhs.second > rhs.second;} );
for ( const auto & item : vector )
if (item.second == 1)
::cout << item.first << ": " << item.second << std::endl;
}
int main(void)
{
vector <string> File;
File.push_back("data.txt");
File.push_back("data_1.txt");
File.push_back("data_2.txt");
File.push_back("data_3.txt");
File.push_back("data_4.txt");
File.push_back("data_5.txt");
File.push_back("data_6.txt");
File.push_back("data_7.txt");
File.push_back("data_8.txt");
File.push_back("data_9.txt");
map<string, unsigned int> wordsCount;
for (int i=0; i < File.size(); i++)
{
ifstream fileStream(File[i]);
if (fileStream.is_open())
while (fileStream.good())
{
string word;
fileStream >> word;
if (wordsCount.find(word) == wordsCount.end())
wordsCount[word] = 1;
else
wordsCount[word]++;
}
else
{
cerr << "ERROR." << endl;
return EXIT_FAILURE;
}
}
PrintMap(wordsCount);
return EXIT_SUCCESS;
}
答案 0 :(得分:0)
如果您不想打印仅出现一次的单词,请更改:
if (item.second == 1)
至:
if (item.second != 1)