转换具有不同参数类型的二进制运算函数

Transform Binary Operation Function with Different Parameter Types

本文关键字:类型 二进制运算 函数 参数 转换      更新时间:2023-10-16

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

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

我的变换二进制运算函数有两个不同类型的参数(stringsize_t)。这样做有效/可能吗?我还通过引用传递第二个arg,这样我就可以更改/增加它,这有效/可能吗?

我是否应该改变策略,使用与命名空间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;
}
相关文章: