Efficient use of STL and STL

Source: Internet
Author: User

Efficient use of STL and STL
Efficient use of STL

It is only a matter of choice, all of which are STL, And the write efficiency may be several times different;
Be familiar with the following terms and use STL efficiently;

When an object is large, the pointer container is created instead of the object container.

1) STL works in copy mode. Any elements that need to be put into STL will be copied;
This means that the STL container is a new space opened up in the heap, and our own variables are generally stored in the function stack or another heap space; in order to fully control STL's own elements, and to work on its own site, replication is involved;
If the Copied object is large, the performance cost caused by replication is not small;
For operations on large objects, using pointers instead of objects can eliminate the cost;
2) Only the pointer copy operation is involved, and no constructor or value assignment constructor is called for additional classes;

vecttor <BigObj> vt1;vt1.push_bach(myBigObj);vecttor <BigObj* > vt2;vt2.push_bach(new BigObj());

Note:
1) before the container is destroyed, destroy the objects pointed to by the pointer; otherwise, memory leakage occurs;
2) When using sorting and other algorithms, You need to construct an object-based comparison function. If you use the default comparison function, the result is a comparison based on the pointer size, rather than an object comparison;

Use empty () instead of size () to check whether it is empty

For list, size () will traverse each element to determine the size, time complexity o (n), linear time; and empty always guarantees constant time;

Use interval member functions instead of single-element operations

Using the range member function has the following benefits:
1) fewer function calls
2) Move fewer elements
3) less memory allocation

For example, assign the elements in the lower half of v2 to v1:
UNIT operation:

for (vector<Widget>::const_iterator ci = v2.begin() + v2.size() / 2;ci != v2.end();++ci)v1.push_back(*ci)

Use the range member function assign ():

v1.assign(v2.begin() + v2.size() / 2, v2.end()); 
Use reserver to avoid unnecessary memory allocation (for vector)

When there is not enough space for new elements, the vector will perform the following operations:
1) allocate twice the current space;
2) copy the current element to the new space;
3) release the previous space;
4) place the new value in the specified position of the new space;

If you know the size of the space in advance, the space is pre-allocated to avoid the cost of re-allocating space and copying;
Note: reserve () only modifies the capacity, not the size. adding elements to the vector still needs to be added through push_back;

Use an ordered vector instead of the associated container (applicable for periodic operations)

Definition of phase operations:
After a series of inserts and completes, all subsequent operations are queries;

Using vector has the following advantages in phase operations:
1) The ordered advantage brought by the Association of containers due to vector Order is lost;
2) the query algorithm uses the binary search to access the continuous memory space faster than the discrete space;

Select insert () and operator [] in map

Insert is highly efficient during insertion, because operator first explores whether this element exists. If this element does not exist, it constructs a temporary one, which then involves a value assignment and adds a temporary object structure;
When updating an object, [] is more efficient. insert creates an object and overwrites the original object. [] directly assigns values to the original object;

The default comparison function of the hash function is sort _to, because it does not need to be ordered;

Replace handwritten loops with algorithms whenever possible

1) higher efficiency than handwriting;
STL code is written by C ++ experts, and the code written by experts is difficult to surpass in efficiency;
Unless we give up some features to meet specific needs, it may be faster than stl; for example, based on programming in specific scenarios, we give up versatility and portability;
2) It is not prone to errors;
3) use high-level thinking Programming
Compared with assembly, C is a high-level language; a c language statement requires several pieces of data to be compiled by sink;
Similarly, in the world of STL, we also have high-level terms:
High-level terminology: insert/find/for_each (STL algorithm)
Low-level Vocabulary: for/while (C ++ syntax)
It is easier to think about programming using high-level terms;

Use a member function instead of an algorithm with the same name.

1) based on efficiency considerations, member functions know the specific attributes of their containers and other containers and can utilize these features. General algorithms are not supported;
2) For associated containers, the member function find is based on the equivalent search, while the general algorithm find is based on equality to search; results may be different;

Use the function object instead of the bare function as the input parameter of the algorithm.

Because inline is effective in the way of function objects, while as a function pointer, the compiler generally does not inline the function pointed to by the function pointer; even if inline is specified;
For example:

inline bool doubleGreater(double d1, double d2){    return dl > d2;}vector<double> v;...sort(v.begin(), v.end(), doubleGreater);

This call does not actually pass doubleGreater to sort. It passes a doubleGreater pointer.
A better way is to use function objects:

sort(v.begin(), v.end(), greater<double>())

Note: The experiment conclusion in effcient c ++ shows that using function objects is generally 1.5 times faster than that of a bare function, and the maximum speed is 2 times faster.

Select an appropriate Sorting Algorithm

We need to think about our necessary requirements before sorting. Maybe we only need the first few elements. In this case, we do not need to use the linear time tool such as sort. It may be a better choice to consume less parttition performance;
The efficiency of the following algorithms decreases from left to right:

partition > stable_partition / nth_element / patical_sort / sort / stable_sort

Function Description:
Partition: separates a set into two intervals: meeting and not meeting a certain standard;
Stable_partition: stable version of partition;
Nth_element: gets the first N elements in any order;
Patical_sort: gets the first N elements, which have been sorted;
Sort: sorts the entire interval;
Stable_sort: stable version of sort;

Select the appropriate container

Why does vector not provide the push_front () member method? Because the efficiency is too low, if there are too many needs to be inserted from the front, we should not use vector, but use list;
Concerning the search speed, we should first consider the hash container (non-standard STL containers, such as unordered_map and unordered_set); secondly, the sorted vector and then the standard associated container;

Reference

Effictive STL
Efficient C ++

Posted by: Large CC | 23JUN, 2015
Blog: blog.me115.com [subscription]
Weibo: Sina Weibo

Related Article

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.