简体   繁体   中英

How to reduce for loops in C++

任务

How can I reduce the following program to 2 for loops and 1 print statement:

for (int i = 1; i <= iter; i++)
    {
        for (int j= 1; j <= row; j++) 
        {
            printf("*");
            for (int k = 1; k <= col; k++)
            {
                printf("_");
            }
            printf("*\n");
        }
        printf("\n\n\n");
    }
  • You can use std::string to concatenate all things to print to reduce print statements.
  • You can use the constructor basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() ); to eliminate the innermost for loop.
std::string ret = "";

for (int i = 1; i <= iter; i++)
    {
        for (int j= 1; j <= row; j++) 
        {
            ret += "*";
            ret += std::string(col, '_');
            ret += "*\n";
        }
        ret += "\n\n\n";
    }

printf("%s", ret.c_str());

With the range-v3 library, you don't need any loops at all.

namespace rv = ranges::views;

auto line = "*" + std::string(col, '_') + "*\n";

auto block = rv::repeat_n(line, row) | rv::join;

auto result = rv::repeat_n(block, iter) | rv::join("\n\n\n");

std::cout << (result | ranges::to<std::string>);

Here's a demo .

You can merge any count of loops, using multiplication and rest from division (just the multiplication has not to overflow).

void f(int iter, int row, int col) {
  for (int i = 0; i < iter * row * col; i++) {
    printf("%s%s%s%s", 
           i % col == 0 ? "*" : "",
           "_",
           i % col == col - 1 ? "*\n" : "",
           i % (row * col) == (row * col) - 1 ? "\n\n\n" : "");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM