HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

C++(11/14) intercalate implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationintercalatestackoverflow

Problem

I wrote a simple generic intercalate function (that should be semantically equivalent to the Haskell intercalate).

template 
    auto intercalate(Fwd_It first, Fwd_It last, Out_It destFirst,
                     Fwd_It whatFirst, Fwd_It whatLast) {
        if (first == last) return destFirst;
        *destFirst = *first;
        ++first;
        ++destFirst;

        while (first != last) {
            std::copy(whatFirst, whatLast, destFirst);
            *destFirst = *first;
            ++first;
        }
        return destFirst;
    }


It appears to be working with what I've tested with (empty ranges, different iterator-supporting ranges, different types, etc.).

However, is this:

  • generic enough?



  • clean enough?



  • fast enough?

Solution

I would not cram in the if statement like that:

auto intercalate(Fwd_It first, Fwd_It last, Out_It destFirst,
                 Fwd_It whatFirst, Fwd_It whatLast) {
    if (first == last) return destFirst;
    *destFirst = *first;
    // ...


While this style is okay at times, it may not be too readable in all situations. Single-line statements can still use curly braces, especially if it may need to be maintained. You could also add a new line before the line that follows it.

auto intercalate(Fwd_It first, Fwd_It last, Out_It destFirst,
                 Fwd_It whatFirst, Fwd_It whatLast) {
    if (first == last) {
        return destFirst;
    }

    *destFirst = *first;
    // ...

Code Snippets

auto intercalate(Fwd_It first, Fwd_It last, Out_It destFirst,
                 Fwd_It whatFirst, Fwd_It whatLast) {
    if (first == last) return destFirst;
    *destFirst = *first;
    // ...
auto intercalate(Fwd_It first, Fwd_It last, Out_It destFirst,
                 Fwd_It whatFirst, Fwd_It whatLast) {
    if (first == last) {
        return destFirst;
    }

    *destFirst = *first;
    // ...

Context

StackExchange Code Review Q#54656, answer score: 4

Revisions (0)

No revisions yet.