2016-08-14 106 views
-2

q循环不增加。如果删除中断,它将变成一个无限循环。它只是不适用于q。 k循环正常工作。如果你也可以解释它为什么会发生,我会非常有帮助。请帮忙 !!如何运行q循环(INCREMENT Q)?

#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

你有'while(myVector2 [k]!= myVector [q]){'... – Jarod42

+0

无界限访问什么是无界限访问? –

回答

0

有2个基本的问题与您的代码:

问题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:

此循环将成为无限循环当且仅当myVector2myVector没有共同的元素。在这种情况下,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注意。

+0

谢谢你!你做得很好 –

+0

@DewangGupta我很高兴你的问题解决了! – KostasRim

+0

@ Jarod42哇我怎么错过了,这样一个伟大的通知人。编辑完成。感谢您的观察。 – KostasRim