从向量到链表C++

From Vector to Linked List C++

本文关键字:C++ 链表 向量      更新时间:2023-10-16

我对C++很陌生,我想确保我目前已经设置了我的链表。 该信息以前存储在向量中,但我被分配将其更改为链表。存储的信息是候选人信息,这里是原始代码。 我是否正确设置了我的列表?

struct CandidateInfo {
std::string name;
int votesInThisState;
int delegatesWonInThisState;  };
std::vector<CandidateInfo> stateCandidates;

这是我的诱惑。 欢迎提出建议。

template <typename StatePrimary>
struct CandidateInfo
{
    std::string name;
    int votesInThisState;
    int delegatesWonInThisState;
    StatePrimary state;
    CandidateInfo<StatePrimary>* next;
    CandidateInfo()
    {
        next = 0;
    }
    CandidateInfo
    (const StatePrimary& c,
     CandidateInfo<StatePrimary>* nxt =0)
        : state(c), next(nxt)
    {}
};
template <typename StatePrimary>
struct CandidateInfoHeader
{
    CandidateInfo<StatePrimary>* first;
    CandidateInfoHeader();
};

我会把它作为评论,但我还没有足够的声誉。您没有使用std::list的原因吗?这样您就可以使用您发布的第一个代码段中的代码,即:

struct CandidateInfo {
std::string name;
int votesInThisState;
int delegatesWonInThisState;  };
std::list<CandidateInfo> stateCandidates;

(请注意最后一行从向量到列表的变化)

std::list 是双向链表的 STL 实现。