I'm doing a little practice and when I output by traversing the map through iterators, it sorts it alphabetically . For example in my sample program, it takes a file with some words on several lines and then it accesses by iterator each key of the map and outputs how many times it occurs on a certain line. Let's say I want to sort the map by how many times it occurs in total, would I have to use the algorithm sort, or something else.
here's the code.
Code:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <map>
#include "functions.h"
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::map;
using std::ifstream;
using std::istream;
using std::ostream;
map<string, map<int, int> >
xref(istream&, vector<string> seperate(const string&) = parse);
int main()
{
ifstream in("temp/Sample Block.txt");
map<string, map<int, int> > report = xref(in);
map<int, int> per_line;
//prints the results
typedef map<string, map<int, int> >::const_iterator map_citer;
typedef map<int, int>::const_iterator map_ii_iter;
for(map_citer i = report.begin(); i != report.end(); i++)
{
cout << i->first << " Occurs on lines: ";
per_line = i->second;
for(map_ii_iter j = per_line.begin(); j != per_line.end(); j++)
{
cout << j->first << "-" << j->second << " time(s), ";
}
cout << endl;
}
system("PAUSE");
return 0;
}
map<string, map<int, int> >
xref(istream& in, vector<string> seperate(const string&))
{
typedef vector<string>::const_iterator vec_citer;
//holds the reference table of how many times a word appears on a line
map<string, map<int, int> > ref_table;
int linecount = 0;
string line;
while(getline(in, line))
{
++linecount;
//splits the word into a vector of strings
vector<string> split_words = seperate(line);
//traverses the vector and finds the map associated with it
for(vec_citer i = split_words.begin(); i != split_words.end(); i++)
{
//increments the number of times a word has appeared on the current line
(ref_table[*i])[linecount]++;
}
}
return ref_table;
}
The "functions.h" doesn't have much but some of my other practice functinons and the parse function which parses the current line into a vector of strings.