Idiom for doing something twice in C ++

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 is a clearer way than introducing a new loop variable counting from 0 to 1, especially since it is not 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- this is just some class that I have formulated and not related to the question.)

+5
source share
5 answers

I have some suggestions. See the latest recommendation:

  • In my opinion, it’s insert(it, N , value)beating std::fill_n:

    for ( int i = 0; i < num_pairs; i++ ) {
        cards.insert(cards.end(), 2, Card(i) );
    }
    
  • If the order is not important, you can simply create cards once and duplicate after the fact

    std::copy(cards.begin(), cards.end(), std::back_inserter(cards));
    
  • . : .

    std::vector<Card> cards(num_pairs * 2);
    int i = 0;
    std::generate_n(cards.begin(), num_pairs, [&i] () { return Card(i++/2); });
    

    (, Card . , cards.back_inserter())

  • :

    std::vector<Card> cards;
    cards.reserve(num_pairs*2);
    for (int i = 0; i < num_pairs; ++i)
    {
        cards.emplace_back(i);
        cards.emplace_back(i);
    }
    
+5

, fill_n <algorithm>

for ( int i = 0; i < num_pairs; i++ )
    std::fill_n(std::back_inserter(cards), 2, Card(i));
+10

, . , , . , , ( , ).

+6

, 2 . - jumps ( ) . - num_pairs.

, ( ). loop unwinding/unrolling . , , , , . Idioms design notions, .

+1

If you want to do this very often, write a small useful function:

template<class F>
void repeat(unsigned times, F callback) {
  while (times--) callback();
}

// ...

for (int i = 0; i < num_pairs; i++) {
  repeat(2, [&] { cards.push_back(Card(i)); });
}

I wrote an example on Ideone .


Your first approach may confuse future readers of your code. They might think that the code was there twice by accident. Using this feature avoids confusion.

Achieving performance will be very minimal, even if> 0, since the compiler is likely to build in the function and fully optimize the loop for small ones times. If you are worried about performance, check first.

+1
source

All Articles