gpt4 book ai didi

c++ - 将双向链表重写为 STL 容器

转载 作者:太空宇宙 更新时间:2023-11-04 03:49:55 25 4
gpt4 key购买 nike

我使用双向链表来存储用户。如您所见,从列表中的任何位置删除用户非常容易。我只向 Removefromlist 函数提供指向用户结构的指针。

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 分配了一百个用户,将它们添加到容器中,然后我应该能够删除任何只提供指向容器用户结构的指针的用户。

最佳答案

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);
}

参见 http://www.cplusplus.com/reference/list/list/http://en.cppreference.com/w/cpp/container/list有关 std::list 的更多信息

关于c++ - 将双向链表重写为 STL 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21562312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com