|
-
May 3rd, 2003, 06:39 PM
#1
sorting a multimap
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: air<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 ?!
}
-
May 3rd, 2003, 07:13 PM
#2
Does the code compiles okay? There could be syntax errors.
Kuphryn
-
May 3rd, 2003, 08:22 PM
#3
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:
Code:
#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;
}
-
May 8th, 2003, 10:09 AM
#4
Thanks very much Philip for the helpful reply.
Best Wihses.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|