将双向链表重写为stl容器

时间:2014-02-04 20:07:48

标签: c++ c stl

我使用双向链接列表来存储用户。 正如您所看到的,从列表中的任何位置删除用户都非常简单。我只向Removefromlist函数提供了一个指向user结构的指针。

typedef struct _user {
     ...
    struct _user  *pCtxtBack; 
    struct _user *pCtxtForward;
   } user, *PPER_user;  

PPER_user UserList;  // head of list

VOID Removefromlist(PPER_user lpUser) { //pointer to allocated user

    PPER_user pBack;
    PPER_user pForward;

    pBack       = lpUser->pCtxtBack;
    pForward    = lpUser->pCtxtForward;

    if( ( pBack == NULL ) && ( pForward == NULL ) ) {

        // This is the only node in the list to delete
          UsersList = NULL;
    } else if ( ( pBack == NULL ) && ( pForward != NULL ) ) {

        // This is the start node in the list to delete
        pForward->pCtxtBack = NULL;
    } else if ( ( pBack != NULL ) && ( pForward == NULL ) ) {

        // This is the end node in the list to delete
        pBack->pCtxtForward = NULL;
                    UsersList = pBack;
    } else if( pBack && pForward ) {

       // Neither start node nor end node in the list
        pBack->pCtxtForward = pForward;
        pForward->pCtxtBack = pBack;
    }

    free(lpUser);

}

现在我正在尝试用更多的c ++样式重写我的列表并使用一些stl容器(我对它们知之甚少)。我应该选择哪一个保留Removefromlist功能?例如:我使用 new 分配了一百个用户,将它们添加到容器中,然后我应该能够删除任何只向用户提供用户结构指针的用户。

1 个答案:

答案 0 :(得分:1)

std::list模板实现双向链接列表。

建议的更改:

typedef struct _user {
     ...
    // Not needed: struct _user  *pCtxtBack; 
    // Not needed: struct _user *pCtxtForward;
   } user;  

std::list<user> UserList;  // The container. To get the head of the list
                           // use auto head = std::begin(UserList); 

void Removefromlist(std::list<user>::const_iterator user) { //iterator to user in list

UserList.erase(user);
}

有关std :: list

的mor信息,请参阅http://www.cplusplus.com/reference/list/list/http://en.cppreference.com/w/cpp/container/list