Correctly implementing a singly linked list C++

后端 未结 4 774
無奈伤痛
無奈伤痛 2021-01-26 09:34

I have a list with names of employers such as:

Node 1: Jill, Matt, Joe, Bob, Matt

Node 2: Jeff, James, John, J

4条回答
  •  走了就别回头了
    2021-01-26 10:20

    For what it's worth, I'd probably implement it like this.

    class EmployerCollection
    {
    public:
        typedef std::list EmployerList;
    
    public:
        bool AddEmployer(const std::string& name)
        {
            EmployerList::const_iterator it = std::find(m_employers.begin(), m_employers.end(), name);
            if (it != m_employers.end()) // Already exists in list.
            {
                m_employers.splice(m_employers.begin(), m_employers, it, std::next(it));
                return true;
            }
            m_employers.push_front(name);
            return false;
        }
    
    private:
        EmployerList m_employers;
    };
    
    int main()
    {
        const int NUM_EMPLOYERS = 15;
        std::string employers[NUM_EMPLOYERS] = {"Jill", "Jeff", "Doe", "Pablo", "Loui", "Ron", "Bob", "Joe", "Monica", "Luis", "Edward", "Matt", "James", "Edward", "John"};
    
        EmployerCollection c;
    
        for (int i=0; i

提交回复
热议问题