迭代器丢失值
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时都有自己的迭代器。
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?