Reputation: 4976
I am working with an adjacency list and a map defined using the following type definitions :
typedef vector<list<Edge> > adjacencyList;
typedef map<int,WikiPage> idToWikiMap;
I would like to sort an adjacency list (adjacencyList
) by name. The index of the adjacencyList
is mapped to a pair in my map. For example,
adjacencyList lst;
lst[0] = NULL
lst[1] = list of edges related to City1
lst[2] = list of edges related to City2
idToWikiMap mymap;
mymap[1] -> Name of City1
mymap[2] -> Name of City2
So I want to sort the adjacency list using the name in the map related to the index of the adjacency list. I have come up with the following code. Since my compare function needs the map, I can't just create a normal function. So I used a struct
and Local
.
The compare works. I can cout
the name of the lists currently being compared and the return value. For example, I get
Comparing Chicago and New York
Smaller: 0
Comparing Montreal and Chicago
Smaller: 1
Comparing Montreal and New York
Smaller: 0
Comparing Toronto and Chicago
Smaller: 1
Comparing Toronto and Montreal
Smaller: 1
Comparing Toronto and New York
Smaller: 1
Comparing Miami and Chicago
Smaller: 1
Comparing Miami and Montreal
Smaller: 0
However, the original does not get modified... Did I do something wrong?
void printOrganized(adjacencyList& lst, idToWikiMap page_ofID) {
// Define compare functions that accepts idToWikiMap parameter
struct Local {
Local(idToWikiMap mymap) { this->mymap = mymap; }
bool operator() (const list<Edge>& l1, list<Edge>&l2)
{ return mymap.at(l1.front().origin).title < mymap.at(l2.front().origin).title; }
idToWikiMap mymap;
};
/* Sort adjacenyList lst */
sort (lst.begin()+1, lst.end(), Local(page_ofID));
...
}
Upvotes: 0
Views: 141
Reputation: 3477
Your code worked well for me, after I fixed a compilation error. Maybe your compiler isn't reporting this error, but it's causing your code not to work?
Anyway, the error is in the comparison function - you should get both parameters as const references, i.e.
bool operator() (const list<Edge>& l1, const list<Edge>& l2)
Also, I had to move Local
to the global scope, because it wasn't working for me as long as it was defined inside the function. You can see the working result here: http://ideone.com/e.js/UPMeFm
Upvotes: 1