转换不同参数类型的二元运算函数

Transform Binary Operation Function with Different Parameter Types

我正在尝试使用 std::transform 编辑字符串以输出以下内容:

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

我的变换二进制运算函数有 2 个不同类型的参数(stringsize_t)。难道valid/possible要这样做吗?我还通过引用传递了第二个参数,所以我可以 change/increment 它,这是 valid/possible 吗?

我是否应该改变策略并使用命名空间 algorithm 中的不同函数来实现此目的?也许 shuffle,是否有 < C++11 函数可以实现这一点?

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

我不确定我是否完全理解您的需求,但是这个解决方案怎么样:

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

我已经使用了 13 次迭代来模拟您的原始输出,因此您可以将其更改为您需要的任何数字。

std::transformstd::shuffle (std::random_shuffle) 都没有解决您的问题。有关它们的用法,请参见 cppreference。无论如何,这是我的解决方案,它运行高效。

int main() {
    std::string str = "abcdefghijklmnopqrstuvwxyz{";
    for (int cnt = 1, i = 0; cnt < str.size(); cnt += 2) {
        for (int n = cnt; n; --n) {
            std::cout << str[i];
            i = (i + 1) % str.size();
        }
        std::cout << std::endl;
    }
    return 0;
}