Effective STL (Container part Summary)

Source: Internet
Author: User

Still like effective part of the book, read several times, here the STL and container related to some basic points of attention to summarize, and then to summarize the iterator, etc.

1 for a sequence container to be deleted, the iterator cannot be done in advance with the + + operation as the associated container, because deleting an iterator invalidates himself and the subsequent iterator is invalid, so the value of the next pointer returned by erase should be saved. In the case where the associated container does not cause the subsequent iterator to be invalid

2 in the STL if you use a new operation on the object in the container, be sure to release it, because the destructor is not done, it is best to use a smart pointer, but do not use the auto_ptr pointer, because his copy, the copy of the object will be copied to the value of NULL may cause unpredictable problems

3 If you want to reduce the need to change the type of container to modify the code, then the container should be a typedef substitution, and preferably hidden into a class, the use of interfaces for processing

4 using interval member functions, such as assign, interval constructors, interval insert functions, Interval erase functions, can be better than cyclic invocation of a single element corresponding to the function, from the function call, the change of the value between elements, as well as memory allocation problem to consider

5 for the Sequence container, the list container, as well as the associated container, the use of the deleted element should choose a different delete function, see clause 9, note that this is to delete a separate element, if it is to delete a range of data directly, then the direct use of erase can be

6 Many string behind use the function of counting, eliminating unnecessary memory allocation and character copy, improve the efficiency. However, if it is in multi-threaded situations, it is necessary to pay attention to the consistency of reading and writing

7 reverse function only vector and string have

He can reduce the number of memory redistribution

The emphasis needs to be a distinction between resize and reverse two functions

Resize: Forcing the container to change to a state that contains n elements, if it is smaller than the current size (), then the data at the end is refactored, and if large is initialized with the default constructor

Reverse: Forcing the container to have a capacity of N, corresponding to capacity (), usually resulting in new memory allocations. If n is smaller than the current capacity and the vector does nothing, string sets it to the maximum value in size () and N

Generally after the declaration of the container is performed reverse operation, you can anticipate the size of the case, and then you can predict whether the iterator will fail

8 string has a lot of implementation methods

But basically, you have to have data from the next few parts.

The size of the string

Capacity of memory capacity

The value of the string

A copy of the sub-allocation

Count of references to values

Different implementations can make the device have reference count, often need to copy, or multi-threaded case may be useful, and if it is a small string, whether it will be a separate painting, the creation of the dynamic allocation of memory amount, etc., see the 15th data

9 If there is a function for the C API

void dosomething (const int* pints,size_t numints);

void dosomething (const char* pints);

For vectors that can be passed directly to &v[0], it is generally not recommended to pass in V.begin () because he is an iterator after all, but when passed in you need to tell if the container is empty.

For string there is a special function, S.C_STR (), which does not need to determine whether it is empty

After the general introduction, it is best to set as read-only mode, if the additions and deletions, then may directly affect the previous container, causing some unforeseen effects

If the C function initializes the container, the vector can be used to perform an intermediate dump operation, see section 16 for details

10 If you want to remove some of the excess capacity in vector,string, erase mainly removes the size of the capacity, but does not reduce the capacity, in order to compress to the appropriate size using the Swap method

Vector<contestant> (V2). Swap (V2)

string S; String (s). Swap (s)

By creating a temporary variable, only the existing element is copied and then swapped

Also note: Not that after the memory is just the element of memory and may also have a certain retention

Also: the previous iterator and, pointers, references, and so on, are not invalidated

It is best not to use the vector<bool> container in one vector, because he is not a real container, just a container. There is no way he can take the position to operate through the operator []. Because a bool is implemented as a bitwise store, it occupies only one bits. In order to fit the [] operation, an adapter is encapsulated to return a suitable class. So much trouble

If you must use a bool container, then it is recommended to use deque<bool> (as opposed to the vector function just without reverse and capacity operations) and bitsize (also compact storage, the function in the C + + standard library)



12 There are two concepts in the associative container, equality and equivalence

The Find function of a non-member function is generally using equal, operator = = value based on the data is equal eaqul_to function

Insert operation for non-member functions, because to determine whether there is the same key, so the main point is to determine the position of the sorted data, in which the equivalence is mainly through the operator < judgment, less function

Each standard container uses the user's own defined Key_comp to judge, the default function is the less function, can be set by itself, and then as long as the use of member functions to access, then the comparison can be unified.

And it's best to use equivalent concepts in associative containers related to sorting

Because if the equality of the case to insert two actually equivalent data, but in the sort of time and no way to separate sorting, then can not be in a certain way to access the value of key, such as Multiset


But the main point here is to refer to the associative container with sort, for not the standard associative container:

Hash_set Hash_multiset hash_map Hash_multimap

These associative containers are not stored in a sorted manner

Their comparison function is equal_to.


13 Review the application of traits


14 If you want to print a value in a container, you can use the copy function to tell the value into an output stream

Copy (Ssp.begin (), Ssp.end (),ostream_iterator<string> (count, "\ n"))

There is also a need to pay attention to the point is that in the introduction of some comparison function when the need is actually a type, not a function pointer, if it is a function pointer, directly declare a function can be ... It is important to note that if a type

Then the general choice is a struct type after creating a function

struct differ{

Template<typename ptrtype>

BOOL Operator () (Ptrtype p1,ptrtype p2)

{

return *P1 < *P2;

{

}

Called when the set<string*, differ> SSP


15 feel 21 advice really dizzy Ah, looked at a few times to figure it out

The main container is that although there is an equivalent judgment function such as compare but the final judgment is equivalent and there is an outer layer of judgment

! (Compare (A1,A2)) &&! (Compare (A2,A1))

If the Compare function determines that two equal numbers are equal, the result is that the two numbers are not equivalent, and the error

So for the equal number, compare should return false, in fact here the compare should be understood as whether a value is in front of another value, if two values are equal, then his value is of course no positional relationship, so should return false


16 for the Set map type, if you need to modify the corresponding key

The type in map is Pair<k,v>, where K is the const type, so it is not allowed to modify directly

In set the element is not const, because the type may be defined as a struct or class type, in the process of sorting, according to an element to sort, then in the modification of the time he is not able to modify, but for other parts, can be modified.

Because if you modify it directly, it may affect the previous sorting situation

If you must make changes, it is best to copy the elements, modify, delete and reinsert


17 in the process of considering the sort vectors:
Because the map is stored according to the balanced binary tree, if you just want to improve the speed of the query, then the use of the hash container (constant time) is far better than the standard container log time, but if the hash table is small, may make the performance of the lookup poor

At the same time in the map storage because there are some additional pointers to the cost, while the role of brothers in the weak storage is not adjacent. So if the volume is large, such as across multiple memory pages, it may be relatively slow.

Relative to the sort of vector, if the adoption of binary_search may be faster, but because it is the case of vectors, so the data must be required to delete and remove the operation is very small, but also to simulate the pair of some operations, here a note is that, The key in the map is const, but it cannot be defined as const when simulating in vector, because there will be a lot of copy operations, etc.


18 for the operation of the map, [] The operation has a different meaning, if the key is not in the original data structure, then the insert operation, if already have, then the corresponding is the modification operation

For high efficiency,

If it is OK to know that it is an insert, it is best to take the insert operation. Because if [], is to insert a constructor corresponding to the pair data, and then modify the data, rather than directly inserted

If it is a modification, it is done directly [], because if you are using INSERT, the value [] is modified to insert



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Effective STL (Container part Summary)

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.