我正在获取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;

关于c++ - vector 的std::find()错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6965585/

10-13 06:28