CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2003
    Posts
    38

    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 ?!
    }

  2. #2
    Join Date
    Feb 2002
    Posts
    5,757
    Does the code compiles okay? There could be syntax errors.

    Kuphryn

  3. #3
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    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;
    }

  4. #4
    Join Date
    Jan 2003
    Posts
    38
    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
  •  





Click Here to Expand Forum to Full Width

Featured