c++循环在第一次运行后跳过

C++ Loop Skips After First Run

本文关键字:运行 第一次 循环 c++      更新时间:2023-10-16

我有一段代码,在我的生命中我不明白为什么循环在第一次运行后跳过。

if (*itr2 != 0)
     {
         int s = *itr2;
         //cout << s << endl;
         k = k + s;
         cout << "X: " << x << " K: " << k << " S: " << s << endl;
             for (int i = x; i < s; i++)
             {   
                 cout << "test" << endl;
                 string value = allSub[i];
                 cout << value << endl;
                 vector<string>::iterator it2;
                 vector<string>::iterator it3;
                 it2 = find(subCode.begin(), subCode.end(), value);
                 int pos = distance (subCode.begin(), it2);
                 adMatrix [pos][pos] ++;
                    for (int v = 0; v < i; v++)
                    {
                        string value2 = allSub[v];
                        cout << "does it run: " << value2 << endl;
                        it3 = find(subCode.begin(), subCode.end(), value2);
                        int pos2 = distance (subCode.begin(), it3);                           
                        adMatrix [pos][pos2] ++;
                        adMatrix [pos2][pos] ++;
                    }  
                 x = i;
             }
        x++;
     }

假设x和k初始化为0。输出如下:

 X: 0 K: 4 S: 4
 test
 CSCI203
 test
 CSCI235
 does it run: CSCI203
 test
 CSCI222
 does it run: CSCI203
 does it run: CSCI235
 test
 CSCI205
 does it run: CSCI203
 does it run: CSCI235
 does it run: CSCI222
 X: 4 K: 7 S: 3
 X: 5 K: 11 S: 4
 X: 6 K: 13 S: 2
 X: 7 K: 17 S: 4

为什么x = 4之后的值不运行for循环?

for(int i = x; i < s; i++) {

检查后面的迭代:s小于x,因此初始化i大于s,并且循环永远不会执行。