Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you used a <code>std::vector&lt;Card&gt;</code> instead of a C array, and you overloaded <code>operator&lt;</code> for <code>Card</code>, you can get the standard library to shuffle and sort the deck for you.</p> <p><code>vector&lt;T&gt;</code> is a <strong>container</strong> that comes with standard library. It's a class template that can store elements of type <code>T</code>. <code>T</code> can be a number type, a <code>std::string</code> or even a <code>struct</code> or <code>class</code>.</p> <p>Here's how you overload the less-than operator for <code>Card</code>:</p> <pre><code>bool Card::operator&lt;(const Card&amp; other) { return true if this card is smaller than the other card; // You may want to order by rank, then by suit, or vice-versa. } </code></pre> <p>With this operator defined, standard library containers and algorithms will now "know" how to order your <code>Cards</code>.</p> <p>Here's how you can use a <code>vector</code> of <code>Card</code>s.</p> <pre><code>std::vector&lt;Card&gt; deck(52); // Initially sized to 52 elements // Populate deck just like you would an array deck[0] = Card(diams, ace); etc... // Sort the deck std::sort(deck.begin(), deck.end()); // Shuffle the deck std::random_shuffle(deck.begin(), deck.end()); // Get the 5th card in the deck Card fifth = deck[4]; </code></pre> <p><code>std::sort</code> uses the quicksort algorithm, which is much faster than the bubble sort you've written (no offence :-). It's hard to write hand-made data structures and algorithms that can beat what the standard library provides. Compiler writers have spent years perfecting and tuning their standard library implementations.</p> <p>When you use standard library containers, you have an arsenal of standard library algorithms at your disposal. This allows you to concentrate on solving problems, and not rewriting the same basic algorithms and data structures over and over.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload