Skip to the content of the web site.

Project W.11: Print an array

Write the following function prints an array.

Integer implementation

void print( int array[], std::size_t capacity,
                         std::size_t max_leading = 0,
                         std::size_t max_trailing = 0,
                         char *opening_delimiter = "{",
                         char *closing_delimiter = "}",
                         char *separator = "," );

void print( int array[], std::size_t capacity,
                         std::size_t max_leading = 0,
                         std::size_t max_trailing = 0,
                         std::string opening_delimiter = "{",
                         std::string closing_delimiter = "}",
                         std::string separator = "," );

where an array is printed as follows:

  • The opening delimiter is printed,
  • If both maximum leading and trailing entries are 0, or the number of entries is greater than or equal to the sum of the maximum leading and trailing entries to be printed, all entries of the array are printed separated by the separator string,
  • Otherwise, the specified number of leading entries is printed, separated and followed by the separator string, followed by the string "..." being printed, followed by the separator string and the specified number of trailing entries is printed, separated by the separator string.

For templated implementations, you could compare to 0, but it is better to compare to the default value of the templated type: T{}.

template <typename T>
void print( T array[], std::size_t capacity,
                       std::size_t max_leading = 0,
                       std::size_t max_trailing = 0,
                       char *opening_delimiter = "{",
                       char *closing_delimiter = "}",
                       char *separator = "," );

template <typename T>
void print( T array[], std::size_t capacity,
                       std::size_t max_leading = 0,
                       std::size_t max_trailing = 0,
                       std::string opening_delimiter = "{",
                       std::string closing_delimiter = "}",
                       std::string separator = "," );

Example printouts

    int array[10]{11, 12, 13, 14, 15, 16, 17, 18, 19, 20};

    print_array( array, 10 );
    std::cout << std::endl;
    print_array( array, 10, 5 );
    std::cout << std::endl;
    print_array( array, 10, 4, 2 );
    std::cout << std::endl;
    print_array( array, 10, 0, 0, "[", "];", ", " );
    std::cout << std::endl;
    print_array( array, 10, 7, 1, "[", "];", ", " );
    std::cout << std::endl;
    print_array( array, 10, 0, 4, "[", "];", ", " );
    std::cout << std::endl;

The output would be

{11,12,13,14,15,16,17,18,19,20}
{11,12,13,14,15,...}
{11,12,13,14,...,19,20}
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
[11, 12, 13, 14, 15, 16, 17, ..., 20];
[..., 17, 18, 19, 20];