jeudi 16 avril 2015

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);
}

Aucun commentaire:

Enregistrer un commentaire