CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2009
    Posts
    46

    Sorting string by arbitrary method

    I'm programming a card game and want to be able to sort by value, so if someone has an Ace "A", then that would have a higher value than someone with a 10, 'T', or a Jack 'J'. I'm been looking through by STL book, but can't quite find a way to do this. I assume I though I would be able to put these keys in a map and then associate a value to them, but I want the value to only apply to the first character in the string (since all the string will have 2 values, the card and the card suite, so a string would be like 'As' for Ace of spades). Thanks.

    Sysop1911

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Sorting string by arbitrary method

    The STL is designed to work with arbitrary comparators. Just design one to match your requirements and then we can help you use it in a container.

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Sorting string by arbitrary method

    Quote Originally Posted by sysop1911 View Post
    I'm programming a card game and want to be able to sort by value, so if someone has an Ace "A", then that would have a higher value than someone with a 10, 'T', or a Jack 'J'. I'm been looking through by STL book, but can't quite find a way to do this. I assume I though I would be able to put these keys in a map and then associate a value to them, but I want the value to only apply to the first character in the string (since all the string will have 2 values, the card and the card suite, so a string would be like 'As' for Ace of spades). Thanks.

    Sysop1911
    This is what Lindley is speaking of:
    Code:
    bool SortCardByValue(const Card& c1, const Card& c2)
    {
        if (c1 comes before c2 when ordered by value)
           return true;
        return false;
    }
    Given two cards, c1 and c2, write the criteria to determine if c1 comes before c2 in an ordered list. I am assuming that Card is the type that describes one of your cards.

    Basically, you are never writing a sort -- all you're doing is telling the sort how to determine, given two items, which one would be placed before the other.

    Once you write that logic, then you can just plug that function or functor that looks similar into std::sort or some other container such as map that requires sorting.

    Regards,

    Paul McKenzie

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