ok ok i got it now right i copy it to vector and sort it..... here is the code
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <map>
#include <vector>
using namespace std;
typedef map<string,int> word_count_list;
struct val_lessthan : binary_function < pair<string,int>, pair<string,int>, bool >
{
bool operator() (const pair<string,int>& x, const pair<string,int>& y) const
{return x.second<y.second;}
}val_lt;
int main()
{
word_count_list word_count;
string filename;
// Get the filename.
cout << "Enter the file you wish to have searched:\n";
cin >> filename;
// Open file.
ifstream file(filename.c_str());
// Read in all the words.
string word;
while (file >> word){
// Remove punctuation.
int index;
while ((index = word.find_first_of(".,!?\\;-*+")) != string::npos)
word.erase(index, 1);
++word_count[word];
}
//copy pairs to vector
vector<pair<string,int> > wordvector;
copy(word_count.begin(), word_count.end(), back_inserter(wordvector));
//sort the vector by second (value) instead of key
sort(wordvector.begin(), wordvector.end(), val_lt);
for(int i=0; i<wordvector.size(); ++i)
cout << wordvector[i].first << " = " << wordvector[i].second << endl;
return 0;
}
to finish the porgram. i need to output the 20 most common or used words....
i try changing
for(int i=0; i<wordvector.size(); ++i)
to for9int i=0,i<=20;i++)
but nothing happens
markrezak
-8
Newbie Poster
Recommended Answers
Jump to PostThis should do it
vector<pair<string,int> >::iterator it; for(it = wordvector.begin(); it != wordvector.end(); it++) cout << (*it).first << " = " << (*it).second << "\n";
Jump to Post>>am i missing something?
Just add a counter, when it reaches 20 then stop the loop. Also, pay attention to the quantities that are displayed because the smallest ones are sorted to the top, not to the bottom. So the first 20 items in that array will be the smallest, …
All 5 Replies
markrezak
-8
Newbie Poster
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
markrezak
-8
Newbie Poster
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
markrezak
-8
Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.