Tarupron
Tarupron

Reputation: 548

Accessing numerous elements of an iterator

This is probably going to be rather simple but the solution is currently eluding me. Here is a brief run down of the program.

The program displays and allows the user to shuffle the cards, then display them again on user input in shuffled form. Currently my output comes in a single line, until it forces itself to make a new line from exceeding the window size.

What I need to do is create 4 separate lines of 13 cards, the way I had this in pseudocode is:

if(deck[12])
   cout << endl;

However I'm having trouble getting it to access the elements of the iterator so that it can end the line after 13 cards have been displayed. Here is my for loop that displays the cards:

for (vector<const string*>::const_iterator it=deck.begin(); it!= deck.end(); ++it)
            {
                cout << (*it)->c_str() << ' ';
            }

Upvotes: 0

Views: 63

Answers (3)

Pete Becker
Pete Becker

Reputation: 76305

You've got 52 cards, and want to show them in 4 lines of 13 cards each. That's easy:

for (int line = 0; i < 4; ++i) { for (int card = 0; card < 13; ++card) std::cout << *it++); std::cout << '\n'; }

where it gets initialized to point to the first card in the deck. Note that the code assumes that the objects stored in the deck can be inserted directly into an ostream. Change const string* to string; you'll find that your life is much simpler.

Upvotes: 0

Mahesh
Mahesh

Reputation: 34625

You can do something like this -

 if ((it - deck.begin()) % 13 == 0)
 {
     std::cout << "\n";
 }

Upvotes: 2

jrok
jrok

Reputation: 55395

How about a separate counter?

int n = 0;
for (vector<const string*>::const_iterator it=deck.begin(); it!= deck.end(); ++it)
{
    cout << (*it)->c_str() << ' ';
    if (++n == 13)
    {
        n = 0;
        cout << '\n';
    }
}

Upvotes: 2

Related Questions