开发者

Error with std::find() for a vector

I am getting RUN FAILED (exit value 1, total time: 493ms). I get it when I try to check if a vector has an element from an array in it:

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

The full code of the program:

#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 开发者_JS百科(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;
}

When I comment a piece of code that does the searching, it builds and runs okay. Hope you'll be able to help me. Thanks in advance.


You might think that local variables automatically have initial value of zero when you define them. That's not the case. For a non-static local variable of build-in type without an initializer, its initial value can be anything.

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

You may define them as

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


Seems like you don't give ind an initial value before using it as an index

ind = permutation[ind] - 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜