STL 列表<mystruct>返回问题
STL list<mystruct> return problem
我正试图在项目中使用STL列表,但我遇到了以下问题。
我希望我的列表存储一个结构。例如,这个
struct mystruct
{
int x;
int y;
};
然后我使用迭代器访问列表中的每个结构,如下所示。
list<mystruct> L;
list<mystruct>::iterator lit;
for(lit=L.begin();lit!=L.end();lit++)
{
if(lit->x==1) cout << "<NUM," << lit->x << "> ";
if(lit->y==2) cout << "<ID," << lit->y << "> ";
}
这是可行的,但我想一次得到一个结构,所以我做了这个函数
mystruct Myclass::next(void)
{
if(lit!=L.end())
{
lit++;
}
return *lit;
}
但我在运行它后遇到了一个错误,我不明白为什么会发生这种情况。
有什么问题吗?
mystruct Myclass::next(void)
{
if(lit!=L.end())
{
lit++;
}
return *lit;
}
除非你已经在最后,否则你会递增,但无论你是否在最后,每次都会取消引用。为了解决这个问题,可以考虑返回一个指针,如果在末尾,则返回一个0
指针。
mystruct* Myclass::next(void)
{
if(lit!=L.end() && ++lit != L.end())
{
// dereference to get the struct, and then return the address of the struct
return &*lit;
}
return 0;
// or nullptr in C++0x
}
然后再次检查使用Myclass::next
的代码中的0
(或nullptr
(。
如果您正在编写返回对象(而不是指针(的next()
,那么我认为您还需要编写has_next()
函数,在调用next()
之前,您应该调用该函数来检查列表中是否有项。类似这样的东西:
bool has_next()
{
list<mystruct>::iterator temp = lit;
return ++temp != L.end();
}
mystruct Myclass::next(void)
{
if( !has_next())
{
throw "end of the list is reached";
}
++lit;
return *lit;
}
//usage
while(myClassInstance.has_next())
{
mystruct s = myClassInstance.next();
//work with s
}
或者,若您决定从next()
返回指向mystruct
的指针,那个么就不需要has_next()
了。你可以这样写:
mystruct * Myclass::next(void)
{
++lit;
if( lit == L.end() )
return NULL;
return &(*lit);
}
问题就在这里:
mystruct Myclass::next(void)
{
if(lit!=L.end())
{
lit++;
}
return *lit;
}
首先,照明是如何定义的
其次,如果lit等于L.end((,则应该返回一些默认值,而不是取消引用它,因为如果这样做,则会导致未定义的行为。如果幸运的话,你的程序将会崩溃。
相关文章:
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- 从 C++ 中的函数返回数组地址问题
- 在类中返回结构时出现问题
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 这个返回元素位置的基于循环的函数有什么问题?
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 特征返回类型的 pybind11 问题
- 类的大问题,以及从空函数c++返回
- 基本的 c++ 问题:如果我在函数中创建某些内容并返回它会发生什么?
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 存储另一个函数返回的布尔数组时遇到问题
- 为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
- 从 C++ 中的函数返回双精度的问题
- 返回不停止函数,递归函数问题?(编程练习,动态规划,Levenshtein 回溯)
- 字符 * 未从重载运算符或内存管理问题正确返回
- 带有指针返回问题的c++协方差问题
- 在 c++ 中使用 sqlite 的 void 函数中的"返回"问题
- C++动态矩阵乘法返回问题
- C++ 无限循环,返回问题
- STL 列表<mystruct>返回问题