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

标签 c++ c++11 std stl-algorithm

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

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

我的转换二元运算函数有 2 个不同类型的参数(stringsize_t)。这样做是否有效/可能?我还通过引用传递了第二个 arg,所以我可以更改/增加它,这是有效的/可能的吗?

我是否应该改变策略并使用命名空间 algorithm 中的不同函数来实现此目的?也许 shuffle,是否有

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 次迭代来模拟您的原始输出,因此您可以将其更改为您需要的任何数字。

关于c++ - 转换不同参数类型的二元运算函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29690706/

相关文章:

c++ - 这段 C++ 代码的奇怪行为(std::wcout 和 std::exception)

c++ - 抛出匿名异常子类

c++ - 重置 move 对象的常用惯用法是什么?

c++ - 简单的复制和 move 操作有什么不同吗?

c++ - 返回转发的引用

c++ - 使用索引与迭代器将 vector 迭代到倒数第二个元素

linked-list - 二进制表达式 ('ostream' (又名 'basic_ostream<char>' )和 'void' )的无效操作数

c++ - 在 boost::singleton_pool 中创建对象

java - 了解C++,学习Java需要多长时间?

c++ - C 和 C++ 的某些标准之间的差异