开发者

STL list<mystruct> return problem

I am trying to use STL list in a project but i have the following problem.

I want my list to store a struct. For example this one

struct mystruct
{
    int x;
    int y;
};

Then i am using an iterator to access every struct in the list like this.

list<mystruct> L;
list<mystruct>::iterator lit;
for(lit=L.begin();lit!=L.end();lit++) 
    {
        if(lit->x==1) cout << "<NUM," <<开发者_如何学Python; lit->x << "> ";
        if(lit->y==2) cout << "<ID," << lit->y << "> ";
    }

This works but i want to get one struct at a time so i made this func

mystruct Myclass::next(void)
{
    if(lit!=L.end()) 
    {
        lit++;
    }
    return *lit;
}

but i get an error after running it and i cannot understand why this happens.

Any ideas what is going wrong?


mystruct Myclass::next(void)
{
    if(lit!=L.end()) 
    {
        lit++;
    }
    return *lit;
}

You increment unless you already are at the end, but the dereferencing happens every time, regardless of if you are at the end or not. To help around that problem, consider returning a pointer, and then a 0 pointer if you are at the end.

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
}

And then check agains 0 (or nullptr) in the code where you use Myclass::next.


If you're writing next() that returns an object (rather than pointer), then I think you also need to write has_next() function which you should call to inspect if there is item in the list or not, before calling next(). Something like this:

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
}

Or if you decide to return pointer to mystruct from next(), then has_next() is not so needed. You can write this:

mystruct *  Myclass::next(void)
{
    ++lit;
    if( lit == L.end() ) 
         return NULL;
    return &(*lit);
}


The problem is here :

mystruct Myclass::next(void)
{
    if(lit!=L.end()) 
    {
        lit++;
    }
    return *lit;
}

First how is lit defined?
Second, if lit is equal to L.end() you should return some default value, not dereference it, because if you do, you are causing an undefined behaviour. If you are lucky, your program will crash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜