转换具有不同参数类型的二进制运算函数
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
我的变换二进制运算函数有两个不同类型的参数(string
和size_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::transform
和std::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;
}
相关文章:
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- 错误:类型"double()"和"double()"的操作数无效到二进制&quo
- C2679 二进制"<<":未找到采用右操作数类型的运算符
- int* 和 int[] 类型对二进制运算符 + 的操作数无效
- 错误:二进制'operator*' 'float'和'float[0]'类型的操作数无效
- 错误 C2679 二进制"<<":未找到采用类型为 'T' 的右侧操作数的运算符
- 二进制 '==':未找到采用 'Enemy' 类型左侧操作数的运算符(或者没有可接受的转换)
- 类型"int"和"const char [15]"到二进制"运算符<<"的无效操作数^
- 大多数基本类型的高效二进制序列化
- c++ 错误:二进制"运算符+"类型"矩阵*"和"矩阵*"的操作数无效
- 将fwrite转换为C++类型代码以写入二进制文件
- 二进制'operator+' 'int*'和'int*'类型的无效操作数
- 二进制">>":未找到采用类型为"std::p air<int,int>"的右操作数的运算符
- 错误:二进制">>":未找到采用类型为"const char [1] 的右操作数的运算符
- Pascal类型二进制文件的C++和Python类似物
- 转换具有不同参数类型的二进制运算函数
- 确定两个矢量类型或一个矢量类型与标量类型之间的二进制运算结果的正确大小类型
- c++中的动态(类型)二进制缓冲区
- 二进制运算转换-G++不编译,但VS编译