razshan
razshan

Reputation: 1138

How to print a new line in C++ using vectors?

I want to print a new line after printing out certain indexes [0], v[2], v[6], v[14]. increments of 2^(n+1)

for (int i = 0; i < v2.size(); i++)
{   
    std::cout << v2[i] << " ";
    // need to print a new line after done printing v[0], v[2], v[6], v[14] 
}

I tried hard coding if(i== 0 || i == 2 || i == 4 || .. || i == 30) but that seems not so efficient. Any suggestions?

Upvotes: 0

Views: 648

Answers (3)

James Kanze
James Kanze

Reputation: 153909

Supposing Roddy is right, and in fact, you want the length of each line to increase to the next power of two, the problem is easily solved using a variation on the standard idiom:

int maxInLineCount = 2;
int inLineCount = 0;
for ( auto current = v.begin(); current != v.end(); ++ current ) {
    if ( inLineCount != 0 ) {
        std::cout << ' ';
    }
    std::cout << *current;
    ++ inLineCount;
    if ( inLineCount >= maxInLineCount ) {
        std::cout << '\n';
        inLineCount = 0;
        maxInLineCount *= 2;    //  This is the added bit.
    }
}
if ( inLineCount != 0 ) {
    std::cout << '\n';
}

Upvotes: 0

user258808
user258808

Reputation: 734

As a starting point, try this:

unsigned uNext = 0, power = 0;
for (unsigned i = 0; i < v2.size(); ++i) {
  cout << v2[i] << (i == uNext) ? endl : " ");
  uNext = (uNext == i) ? uNext + pow(2, ++power): uNext;
}

You have to check that you do not overflow the unsigned uNext so add some checks.

Upvotes: 0

Roddy
Roddy

Reputation: 68033

Try this.

    if ((i & (i+1)) == 0) // print newline if i+1 is a power of two

Upvotes: 2

Related Questions