向量的std :: find()出错

时间:2011-08-06 08:07:05

标签: c++ vector find

我得到了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;
}

当我评论一段执行搜索的代码时,它会构建并运行正常。希望你能帮助我。提前谢谢。

2 个答案:

答案 0 :(得分:1)

似乎在将ind用作索引

之前没有给出ind = permutation[ind] - 1; 初始值
{{1}}

答案 1 :(得分:1)

您可能认为局部变量在定义时会自动将初始值设置为零。事实并非如此。 对于没有初始化程序的内置类型的非静态局部变量,其初始值可以是任何

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

您可以将它们定义为

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