Search code examples
c++c++11stdstl-algorithm

Transform Binary Operation Function with Different Parameter Types


I am attempting to use std::transform to edit a string to output the following:

a  
bcd  
efghi  
jklmnop  
qrstuvwxy  
z{abcdefghi  
jklmnopqrstuv  
wxyz{abcdefghij  
klmnopqrstuvwxyz{  
abcdefghijklmnopqrs  
tuvwxyz{abcdefghijklm  
nopqrstuvwxyz{abcdefghi  
jklmnopqrstuvwxyz{abcdefg  

My transform binary operation function has 2 parameters of different type (string and size_t). Is it valid/possible to do this? I am also passing the second arg by reference so I can change/increment it, is this valid/possible?

Should I maybe change tact and use a different function from the namespace algorithm to achieve this? Maybe shuffle, is there a < C++11 function that can achieve this?

void solution1()
{
    // Easy solution

    std::string testStr = "abcdefghijklmnopqrstuvwxyz{";
    size_t index = 1;

    while (index < testStr.length()) {

        std::string back  = testStr.substr(0, index);
        std::string front = testStr.substr(index, std::string::npos);

        testStr = front + back;
        index += 2;
        std::cout << back << std::endl;
    }
}

// anyway to initialise gIndex to 1?
std::string outputOddGroup(std::string str, size_t& gIndex)
{
    // Is there a better way to split and rebuild the string? 
    std::string back  = str.substr(0, gIndex);
    std::string front = str.substr(gIndex, std::string::npos);

    gIndex += 2;
    std::cout << back << std::endl;
    return front + back;
}

void solution2()
{
    std::string testStr = "abcdefghijklmnopqrstuvwxyz{";
    std::transform(testStr.begin(), testStr.end(), testStr.begin(), outputOddGroup);
}

Solution

  • I'm not sure I fully understand your need but how about this solution:

    #include <iostream>
    #include <string>
    #include <algorithm>
    
    int main()
    {
        std::string testStr = "abcdefghijklmnopqrstuvwxyz{";
        for(size_t i = 0; i < 13; ++i)
        {
            std::cout << testStr.substr(0, i*2 + 1) << "\n";
            std::rotate(testStr.begin(), testStr.begin() + i*2 + 1, testStr.end());
        }
        return 0;
    }
    

    I've used 13 iterations just to mimic your original output so you can change it to whatever number you need.