Here is my original code. I have two functions, add and print_out. "add" is used to update the times of a url by incrementing one every time when a user use that. And print_out just print all of urls that have bee used in order of times.
# include<iostream>
# include<unordered_map>
# include<set>
# include<string>
# include<utility>
using namespace std;
struct compare { // simple comparison function
public:
bool operator()(const pair<string, int>& x, const pair<string, int> &y) const
{ return x.second > y.second; } // returns x>y
};
class Sol{
set< pair<string, int>, compare > db;
// the unordered_map is used to store the iterator of a url in my set, db, so that I can pull the pair of this url later, and update it.
unordered_map< string, set< pair<string, int> >:: iterator > table;
public:
Sol(){};
void add( string url);
void print_out();
};
void Sol :: add( string url){
// when a url is used, the times of it increments by it. If this url is used for the first time, then just insert new pair { url, 1 } into my set.
if( table.find( url ) != table.end() ){
int times = (*table[url]).second +1;
db.erase( table[url] );
db.insert( { url, times} );
table[url] = db.find( { url, times} );
}
else{
pair<string, int> p = { url, 1};
db.insert( p );
}
return;
}
void Sol :: print_out(){
// print out all of urls in order of times they have been used so far
for( auto ite = db.begin() ; ite != db.end() ; ite++ )
cout<< (*ite).first << " " << (*ite).second<<"\n";
return;
}