【问题标题】:How do I run the q loop (INCREMENT Q)?如何运行 q 循环(INCREMENT Q)?
【发布时间】:2016-08-14 13:36:28
【问题描述】:

q 循环不递增。如果删除 break 它会变成一个无限循环。它只是不适用于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;
}

【问题讨论】:

  • 我无法弄清楚是什么导致了问题。我是第一次处理向量。
  • 您对while(myVector2[k] != myVector[q]){的访问权限越界...
  • 什么是越界访问??
  • @DewangGupta 检查答案

标签: c++ loops vector while-loop infinite-loop


【解决方案1】:

您的代码存在 2 个基本问题:

问题一:

你为什么要打破循环? break的准确定义是: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 &lt; 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 &lt; myVector2.size()) 时才会执行,例如防止越界访问。

感谢Jarod42 关注。

【讨论】:

  • @Jarod42 哇,我怎么会错过这个,这么棒的通知人。编辑,完成。感谢您的观察。
猜你喜欢
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 2015-01-18
  • 2018-08-02
  • 2020-05-30
  • 2019-01-07
  • 2014-10-15
相关资源
最近更新 更多