Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiom for doing something twice in C++

Tags:

c++

idioms

Is there a common idiom for doing something twice, as in the following situation?

    for ( int i = 0; i < num_pairs; i++ ) {
        cards.push_back( Card(i) );
        cards.push_back( Card(i) );
    }

I have a feeling that there's a clearer way than introducing a new loop variable counting from 0 to 1, especially since it isn't used except for counting.

    for ( int i = 0; i < num_pairs; i++ )
        for ( int j = 0; j < 2; j++ )
            cards.push_back( Card(i) );

(Card is just some class I made up and not relevant to the question.)

like image 922
Andreas Avatar asked May 22 '12 19:05

Andreas


People also ask

What is the meaning of twice?

Twice; two times in a row. Usually used to emphasize that something is excessive or has an excessive effect. The student had enough alcohol in his system to kill a person twice over. Having to deal with the insurance company after my husband's death has made me suffer twice over.

What is a good sentence for Think Twice?

think twice. COMMON If you think twice about doing something, you consider it again and usually decide not to do it. She'd better shut her mouth and from now on think twice before saying stupid things. If they don't enjoy the experience, they will think twice before they visit again.

What does 'bite off more than you can chew' mean?

Proverbs are well-known for stating a piece of advice or general fact. For example, ‘a picture is worth a thousand words’ is a proverb – a general truth. Let us consider the idiom ‘ bite off more than you can chew ‘. What you meant is that you are trying to do something that is too hard for you.

Why is it easier to remember words than idioms?

It is comparatively easier to remember words unlike idioms because idioms (phrases) contain 3 or more words. And, remembering a chain of words and then speaking them in the correct sequence is not easy.


2 Answers

You probably want to use the fill_n function in <algorithm>

for ( int i = 0; i < num_pairs; i++ )
    std::fill_n(std::back_inserter(cards), 2, Card(i));
like image 67
Collin Dauphinee Avatar answered Oct 24 '22 13:10

Collin Dauphinee


Personally I would just leave it how it is. It looks clean, it's easy to understand, and it's quite readable. Just leave a comment mentioning why you do it twice (but you would do that no matter what).

like image 33
rekh127 Avatar answered Oct 24 '22 12:10

rekh127