简体   繁体   中英

Questions about std::list C++

I'm new to the whole stl business and I have one question. Before using stl my list nodes would be like this :

Class node
{
    int duration;
    string name;
    node * next;
    node * previous;
};

So my question is that when I m about to use stl do i need the node * next and node * previous or they are completely useless since std::list makes ammend for them with their own next and previous functions?

And one more question, do you guys prefer using std::list or making your own? Because this is gonna be my first time using std::list and Im quite buffled.

Thanks for your time.

No you don't need next and previous , std::list implements internally the whole linked list mechanism. just:

Class node {
  int duration;
  string name;
};

and define your list as:

std::list<node> myList;

Even better use a std::vector instead of std::list which outperforms in most situations the std::list as it renders more cache friendly.

std::vector<node> myVec;

Another option would be to use a std::pair instead of defining your own struct :

std::list<std::pair<int, std::string>> myList;

However, use of std::pair here is cleary subjective. I find it more handy to use std::pair instead of defining struct s with two member variables, due to the fact that I can see the element type of my STL data-structure at the place where is defined.

As 101010 tells, that's the case. Also remember the performance of stl list is good since the allocator they use for those is optimized for memory management.

The classical "add of nodes" routine is mostly implemented as a single allocation (with new (C++) or malloc (C)). Nevertheless you can improve that through static arrays or laying data on vectors and pointing to them. I'm just telling in case you want to build something your own and compare performance.

Also let me note that you are using a double linked list. In many cases you only need one iterator per block stl has the forward_list container.

No, your elements of a std::list do not need to have next and previous members. std::list takes care of such bookkeeping internally.

Generally, I will use a standard container rather than rolling my own, unless I have some particular requirements that the standard containers really don't meet. If std::list is the one that is best suited - it often isn't, but is sometimes - I use that.

Although there is some learning value in trying to create your own containers, that sort of thing is not productive in the long run. The standard containers - assuming a quality implementation - are better than most people can do on their own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM