向量的std::find()出错

Error with std::find() for a vector

本文关键字:出错 find std 向量      更新时间:2023-10-16

我得到了RUN FAILED (exit value 1, total time: 493ms)。当我试图检查向量中是否有数组中的元素时,我得到了它:

if (find(cycles.begin(), cycles.end(), permutation[i]) == cycles.end()) {
     startCycle = permutation[i];
     break;
}

程序的完整代码:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define TESTING_FILE_IN
//#define TESTING_FILE_OUT
#define DEBUG
//#define SHOW_TIMING
vector< int > cycles;
int permutation[1001];
/*
 * 
 */
int main() {
    #ifdef TESTING_FILE_IN
    freopen("in.txt", "r", stdin);
    #endif
    int ind, startCycle, n, count, elemProc;
    scanf("%d", &n); //Number of elements in the permutation
    for (int i = 0; i < n; i++) {
        cin >> permutation[i];
    }   
    // Calculate cycles
    startCycle = 1;
    while (true) {
        cycles.push_back(ind + 1);
        elemProc++;
        ind = permutation[ind] - 1;
        if (ind == startCycle) {
            cycles.push_back(startCycle);
            cycles.push_back(-1);
            count++;
            for (int i = 0; i < n; i++) {
                if (find(cycles.begin(), cycles.end(), permutation[i]) == cycles.end()) {
                    startCycle = permutation[i];
                    break;
                }
            }
        }
        if (elemProc == n)
            break;
    }
    cout << count << endl;
    for (int i = 0; i < cycles.size(); ++i) {
        if (cycles[i] != -1)
            cout << cycles[i] << " ";
        else
            cout << endl;
    }
    return 0;
}

当我对一段进行搜索的代码进行注释时,它会构建并运行良好。希望你能帮助我。提前谢谢。

当您定义局部变量时,您可能会认为它们的初始值自动为零。事实并非如此对于不带初始值设定项的内置类型的非静态局部变量,其初始值可以是任何东西

       v----you should initialize these local variables
   int ind, startCycle, n, count, elemProc;

您可以将其定义为

   int ind = 0, startCycle = 0, n = 0, count = 0, elemProc = 0;

在将ind用作索引之前,似乎没有给它一个初始值

ind = permutation[ind] - 1;