Click to See Complete Forum and Search --> : sorting a multimap


p8mode
May 3rd, 2003, 06:39 PM
Hello.
I want to sort a multimap, based on the keys, among other things so that subsequent searching is efficienter. Isnt this possible? If so, whats wrong with the code below which tries to achieve this? Thanks very much in advance for any help.
Best Wishes,
p8mode

//---------------------------------------
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>

typedef std::multimap<int, int> mimap;
typedef std::pair<int,int> ip;
//--------------
class Ftm // functor
{
public:
operator()(const ip& ip1, const ip &ip2) const
{
return ip1.first> ip2.first;
};
};
//--------------

void main()
{

mimap m;
m.insert(ip(i1, i1));
m.insert(ip(i1, i2));
m.insert(ip(i2, i3));

std::sort(m.begin(), m.end(), Ftm()); // error ?!
}

kuphryn
May 3rd, 2003, 07:13 PM
Does the code compiles okay? There could be syntax errors.

Kuphryn

Philip Nicoletti
May 3rd, 2003, 08:22 PM
A multimap is sorted automatically by key, and has various
fast search functions (when searching by key). The only
tricky thing about your example is that it looks
like you want the multimap sorted by greater instead
of less than. When you declare the multimap, you need to
specify the sorting criteria. Here is an example:


#include <iostream>
#include <map>
#include <functional>

using namespace std;

typedef std::multimap<int, int, greater<int> > mimap;
typedef std::pair<int,int> ip;

int main()
{

int i1 = 1;
int i2 = 2;
int i3 = 3;

mimap m;
m.insert(ip(i1, i1));
m.insert(ip(i1, i2));
m.insert(ip(i2, i3));

std::multimap<int, int, greater<int> >::iterator it;

for (it=m.begin(); it!=m.end(); ++it)
{
cout << (*it).first << " " << (*it).second << endl << endl;
}

// find all elements with key = 1

for (it=m.lower_bound(1); it!=m.upper_bound(1); ++it)
{
cout << (*it).second << endl;
}


return 0;
}

p8mode
May 8th, 2003, 10:09 AM
Thanks very much Philip for the helpful reply.
Best Wihses.