迭代器丢失值

Iterator lose value

本文关键字:迭代器      更新时间:2023-10-16

我正试图编写一段代码,在图中查找循环。但是当我的递归函数返回时,迭代器似乎失去了它的值。这是代码:

#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
vector<int > vec[100]; ///Here i hold the nodes
vector<int > ::iterator it;///Iterator for accessing "vec" elements
int viz[100],n,m;///viz remembers if a node was visited, n is the number of nodes and m the number of edges
void ham(int i)
{
    for(it=vec[i].begin();it!=vec[i].end();it++)
    {
        int j=*it; ///j is just for probing something, no real use
        if(!viz[*it])
        {
            viz[*it]=1; ///the it node is visited
            ham(*it);///I visit this node
            viz[*it]=0;///I consider this node unvisited
        }
    }
    if(i==n)///if i equals n then I print the cycle
    {
        for(int j=1;j<=n;j++)
            if(viz[j])
                cout<<j<<" ";
        cout<<endl;
        return;
    }
}
int main()
{
    ifstream fin("graf.in");
    fin>>n>>m;
    for(int i=1;i<=m;i++)///reading the input and storing it in "vec"
    {
        int x,y;
        fin>>x>>y;
        vec[x].push_back(y);
        vec[y].push_back(x);
    }
    viz[1]=1;///the first node is already visited
    ham(1);///starting from the first node
    return 0;
}

当我的函数返回迭代器时,会得到一个负值。谢谢

vector<int > ::iterator it;

是一个全局变量。每次递归调用ham函数时,它都会被使用和覆盖,因此当ham返回时,迭代器处于错误的状态。将迭代器移动到ham函数中,以便每次调用ham时都有自己的迭代器。