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.)
I’ve got a few suggestions. See the last for my recommendation:
In my opinion
insert(it,N, value)beatsstd::fill_n:If order isn’t important, you could just generate the cards once, and duplicate after the fact
Using a dirty lambda and integer division trick. Warning this has the hallmark of a premature optimization: reduces readability for no good reason.
(assumes
Cardis default-constructible. If not, usecards.back_inserter())My recommendation
The following wins in both performance and expression of intent: