我已经为我的堆栈对象类开发了一个名为"rotate"的方法.我所做的是,如果堆栈包含元素:{0,2,3,4,5,6,7}我需要向前和向后旋转元素.
如果我需要向前旋转2个元素,那么我们将在数组中有{3,4,5,6,7,0,2}.如果我需要向后旋转,或者-3个元素,那么,查看原始数组,{5,6,7,0,2,3,4}
所以我开发的方法运行正常.它只是非常无效的IMO.我想知道我是否可以使用mod运算符包围数组?或者,如果它们是无用的代码,我还没有意识到,等等.
我想我的问题是,我该如何简化这种方法?例如使用较少的代码.:-)
void stack::rotate(int r)
{
int i = 0;
while ( r > 0 ) // rotate postively.
{
front.n = items[top+1].n;
for ( int j = 0; j < bottom; j++ )
{
items[j] = items[j+1];
}
items[count-1].n = front.n;
r--;
}
while ( r < 0 ) // rotate negatively.
{
if ( i == top+1 )
{
front.n = items[top+1].n;
items[top+1].n = items[count-1].n; // switch last with first
}
back.n = items[++i].n; // second …Run Code Online (Sandbox Code Playgroud) 我在c ++中创建一个与命令行输入一起使用的应用程序.我在命令行输入一个字符串
int main(int argc, char** argv)
{
if(argc != 2)
{
cerr << "Invalid number of CMD arguments" << endl;
return 1;
}
string StringValue = argv[1];
cout << StringValue << endl;
}
Run Code Online (Sandbox Code Playgroud)
这项工作很好.现在我想循环字符串中的字符.示例:如果我输入单词"STATES".
^STATES|
|^STATES
S|^STATE
ES|^STAT
TES|^STA
ATES|^ST
TETES|^S
STATES|^
Run Code Online (Sandbox Code Playgroud)
其中"^"是开头和"|" 结束.我该怎么做呢?