Thread: next_permutation

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    80

    next_permutation

    Hi guys,

    I've never used this function before, and have a need for it today. I'm getting a lovely bunch of compiler errors...I swear I'm sending in the iterators that it wants.

    This program is simply a test for me to figure out this function, and make sure I can use it with vectors. I can handle it with simply arrays of simply data types, but things are a little harry now. Any advice?

    Code:
    #include<iostream>
    #include<algorithm>
    #include<vector>
    #include"computer.h"
    
    using namespace std;
    
    int main()
    {
        vector<Computer> computers;
        Computer comp;
        for (int i = 0; i < 4; i++)
        {
            comp.setLetter(i + 97);
            computers.push_back(comp);
        }
        while (next_permutation(computers.begin(), computers.end())) // Problems here?
        {
            for (int i = 0; i < 4; i++)
            {
                cout << computers[i].getLetter();
            }
            cout << endl;
        }
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Apr 2002
    Posts
    80
    Yeah, I figured it out...had to overload my < operator. Dumb me...

    Carry on!

  3. #3
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    You could also have used a predicate function object to make the comparison.
    Code:
    bool CompareComputer(Computer left, Computer right)
    {
      //...
      return true/false;
    }
    
    //...
    
    next_permutation(computers.begin(), computers.end(), CompareComputer)
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  4. #4
    Registered User
    Join Date
    Apr 2002
    Posts
    80
    Yeah, I just wasn't thinking...I've used both methods before in other parts of the stl (priority queues, etc.)

Popular pages Recent additions subscribe to a feed