Reputation: 53
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;
}
Upvotes: 0
Views: 320
Reputation: 171167
std::set
uses its comparator (cmp
) for two things:
Determine ordering of iteration: for two elements a
and b
, if cmp(a, b)
, then a
comes before b
in the order.
Determine item equivalent. If cmp(a, b)
and cmp(b, a)
are both false, the items are considered equivalent and only one of them can be present in the set.
Your comparator is >
on the second element of the pair, and your function add
always sets the second element to 1. Therefore, as far as the set is concerned, all the pairs are equivalent and only the first one will be stored.
Upvotes: 4