Over the years, the use of STL container summary!

Source: Internet
Author: User

1th: Carefully select the type of container.

Standard STL sequence Containers: Vector, String, deque, and list.

Standard STL Associative containers: Set, Multiset, map, and Multimap.

Non-standard sequence containers slist and rope. Slist is a one-way list, rope is essentially a "heavy" string.

Non-standard associative containers hash_set, Hase_multiset, Hash_map and Hash_multimap.

Vector as a substitute for string. (see article 13th)

Vectors as a substitute for standard associative containers. (see article 23rd)

Several standard non-STL containers, including arrays, Bitset, Valarray, Stack, queue, and priority_queue.

Whether you care about how the elements in the container are sorted. If you don't care, select the hash container.

Whether the layout of the data in the container needs to be compatible with C. If compatibility is required, only vectors can be selected. (see article 16th)

Whether the element's lookup speed is a key consideration. If so, consider the hash container, the vector that is sorted, and the standard associative container-perhaps this is the order of precedence.

Do you need transaction semantics for insert and delete operations? If yes, you can only select list. Because in a standard container, only the list provides transactional semantics for inserting multiple elements.

The deque is unique, the iterator may become invalid (the insertion operation only occurs at the end of the container, the deque iterator may become invalid) and the pointer to the data and the standard STL container that the reference is still valid.

2nd: Do not attempt to write code that is independent of the container type.

If you want to write code that works for most containers, you can only use the intersection of their functionality. Different containers are different, and they have very obvious advantages and disadvantages. They are not designed to be exchanged for use.

You cannot write code that is separate from the container, but they may be available (in the case of customer code).

3rd: Ensure that the objects in the container are copied correctly and efficiently.

Copy in,copy out, is the way STL works, its overall design idea is to avoid unnecessary copies. An easy way to make the copy action efficient and prevent the split problem from occurring is to make the container contain pointers rather than objects.

4th: Call empty instead of checking to see if size () is 0.

The reason is simple: empty is a constant time operation for all standard containers, and for some list implementations, size consumes linear time.

5th: Interval member function takes precedence over the corresponding single element member function.

Interval member functions are easier to write, express your intentions more clearly, and they show greater efficiency.

6th: Beware of the most annoying analysis mechanism of the C + + compiler.

It is legal to enclose the form in parentheses, which is illegal in parentheses around the declaration of the entire formal parameter, including the data type and the formal parameter name.

7th: If the container contains a pointer created by the new operation, remember to delete the pointer before the container object is destructor.

The STL is intelligent, but it is not smart to know whether or not to delete the object to which the pointer it contains is pointing. To avoid resource leaks, you must manually delete each of these pointers before the container is refactored, or use the reference counting form of a smart pointer (such as Boost's sharedprt) to replace the pointer.

8th: Do not create container objects that contain auto_ptr.

Copying a auto_ptr means changing its value. For example, a vector called sort ordering containing auto_ptr results in that several elements of the vector are set to null and the corresponding elements are deleted.

9th: Carefully choose the method to delete the element.

To delete all objects of the specified value in the container:

If the container is a vector, string, or deque, the Erase-remove idiom is used.

Seqcontainer C;

C.erase (Remove (C.begin (), C.end (), 1963), C.end ());

If the container is a list, use List::remove.

If the container is a standard associative container, its erase member function is used.

To delete all objects in a container that meet certain criteria:

If the container is a vector, string, or deque, the erase-remove_if idiom is used.

If the container is a list, use list::remove_if.

If the container is a standard associative container, use remove_copy_if and swap, or write an element that loops through the container, remembering that when you pass the iterator to the erase, it is incremented.

Assoccontainer C;

...

Assoccontainer goodvalues;

Remove_copy_if (C.begin (), C.end (), Inserter (Goodvalues, Goodvalues.end ()), badvalue);

C.swap (goodvalues);

Or

for (Assoccontainer::iterator i = C.begin (); I!=c.end ();) {

if (Badvalue (*i)) c.erase (i++);

else ++i;

}

To do something inside a loop (except to delete an object):

If the container is a standard sequence container, write a loop to iterate through the elements in the container, remembering to update the iterator with its return value each time you drop the erase.

If the container is a standard associative container, write a loop to iterate through the elements in the container, remembering that the iterator should be incremented each time the iterator is passed to the erase.

10th: Understand the allocation (allocator) of the contract and restrictions.

11th: Understand the rational use of custom assigns.

12th: Do not have unrealistic dependencies on the thread safety of STL containers.

To an STL implementation you can only expect:

It is safe to read multiple threads.

Multiple threads are safe to write to different containers.

You can't expect the STL library to free you from manual sync control, and you can't rely on any thread support.


13th: Vectors and strings take precedence over dynamically allocated arrays.

If you use new, it means you have to make sure that the delete is in the back.

If you are using a string that is implemented as a reference count, and you run in a multithreaded environment and think that a string's reference count implementation can affect efficiency, you have at least three possible options, and no option is to discard the STL. First, check your library implementation to see if you can disable the reference count, usually by changing the value of a preprocessing variable. Second, find or develop a string implementation that does not use reference counting. Third, consider using vectors rather than strings. The vector implementation does not allow reference counting, so hidden multithreaded performance issues do not occur.

14th: Use the reserve to avoid unnecessary redistribution.

There are usually two ways to use the reserve to avoid unnecessary reallocation. The first way to do this is to use reserve if you know exactly how many elements will eventually be in the container. The second way is to set aside enough space and then, when all the data is added, remove the excess capacity.

15th: Note the diversity of string implementations.

If you want to use STL effectively, then you need to know the variety of string implementations, especially when you're writing code that has to run on different STL platforms and you're facing stringent performance requirements.

16th: Learn how to pass vector and string data to the old API.

If you have a vector V, and you need to get a pointer to only the data in V, so that you can use the data as an array, you just need to &v[0 it, or you can use &*v.begin (), but it's not easy to understand. For string s, the form is S.c_str ().

If you want to initialize a vector with data from the C API, you can use vector and array memory layout compatibility to first write the data to the vector and then copy the data to the STL container that you expect to write to.

17th: Use the swap technique to go out of the spare capacity.

Vector (contestants). Swap (contestants);

The expression vector (contestants) creates a temporary vector, which is a copy of the contestants: This is done by the copy constructor of the vector. However, Vector copy constructors allocate only the required memory for the copied elements, so this temporary vector has no extra capacity. We then swap the data in the temporary vector and the data in the contestants, after which the contestants has the capacity to be removed, the capacity of the original temporary variable, and the capacity of the temporary variable to become the original contestants bloated capacity. At this point, the temporary vector is destructor, freeing up the memory previously occupied by contestants.

The same technique is useful for string:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.