STL 列表<mystruct>返回问题

STL list<mystruct> return problem

本文关键字:返回 问题 gt mystruct lt STL 列表      更新时间:2023-10-16

我正试图在项目中使用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((,则应该返回一些默认值,而不是取消引用它,因为如果这样做,则会导致未定义的行为。如果幸运的话,你的程序将会崩溃。