In which scenario do I use a particular STL container?

后端 未结 10 1040
遥遥无期
遥遥无期 2020-11-22 00:31

I\'ve been reading up on STL containers in my book on C++, specifically the section on the STL and its containers. Now I do understand each and every one of them have their

10条回答
  •  春和景丽
    2020-11-22 01:16

    It all depends on what you want to store and what you want to do with the container. Here are some (very non-exhaustive) examples for the container classes that I tend to use most:

    vector: Compact layout with little or no memory overhead per contained object. Efficient to iterate over. Append, insert and erase can be expensive, particularly for complex objects. Cheap to find a contained object by index, e.g. myVector[10]. Use where you would have used an array in C. Good where you have a lot of simple objects (e.g. int). Don't forget to use reserve() before adding a lot of objects to the container.

    list: Small memory overhead per contained object. Efficient to iterate over. Append, insert and erase are cheap. Use where you would have used a linked list in C.

    set (and multiset): Significant memory overhead per contained object. Use where you need to find out quickly if that container contains a given object, or merge containers efficiently.

    map (and multimap): Significant memory overhead per contained object. Use where you want to store key-value pairs and look up values by key quickly.

    The flow chart on the cheat sheet suggested by zdan provides a more exhaustive guide.

提交回复
热议问题