q循环不会递增。如果删除它会变成无限循环。它只是不适用于q。 k循环工作正常。如果你能解释它为什么会发生,我会非常乐于助人。请帮忙 !!
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace::std;
int main() {
string input;
getline(cin, input) ;
vector<char> myVector(input.begin(), input.end());
vector<char> myVector2(input.begin(), input.end());
sort(myVector2.begin(), myVector2.end());
if(myVector2 == myVector){
cout << "rank :1";
}
else{
int i;
for (i = 0; i < myVector2.size(); i++){
cout << myVector2[i];
}
cout << endl;
int q = 0, k = 0, value = 1, w = 1;
while(q < myVector.size()){
while(k < myVector.size()){
while(myVector2[k] != myVector[q]){
while(w < myVector2.size()){
value = value * w ;
w++;
}
k++;
}
cout << value*k;
cout << endl;
myVector2.erase(myVector2.begin()+k);
for(int j = 0; j< myVector2.size(); j++){
cout << myVector2[j];
}
break;
}
q++;
break;
}
}
return 0;
}
答案 0 :(得分:0)
您的代码存在两个基本问题:
问题1:
你为什么要打破循环?中断的准确定义是:The break statement ends execution of the nearest enclosing loop or conditional statement in which it appears. Control passes to the statement that follows the end of the statement, if any.
您递增q
然后中断while-loop
。
您的代码如下所示:
while(q < myVector.size()){
//code here
q++;
break; // <------------ This will exit the while loop on the first iteration
}
因此,永远不会执行外部循环。
问题2:
当且仅当myVector2
和myVector
没有共同元素时,此循环才会变为无限循环。在这种情况下,k将无限增加,因为从不检查k k < myVector2.size?
while(myVector2[k] != myVector[q]){
while(w < myVector2.size()){
value = value * w ;
w++;
}
k++;
}
要解决此问题,请更改while-loop
while(k < myVector2.size() && myVector2[k] != myVector[q]){
while(w < myVector2.size()){
value = value * w ;
w++;
}
k++;
}
Edit1:从左到右评估logical and statements
。逻辑的右侧只有在满足条件k < myVector2.size())
时才会执行,例如防止越界访问。
感谢Jarod42
注意。