Summary of STL range member functions and interval algorithms, stl range Function Algorithms

Source: Internet
Author: User

Summary of STL range member functions and interval algorithms, stl range Function Algorithms
Summary of STL range member functions and interval Algorithms

Here we summarize the interval member functions and interval algorithms that can replace loops;

Compared with the single element traversal operation, the advantage of using the range member function is:
1) fewer function calls
2) Move fewer elements
3) less memory allocation

When the range member function is not applicable, the interval algorithm should also be used. At least, it is simpler, more effective, and less error-prone than the handwritten loop;

Interval member function interval Construction

Standard containers support range constructor:

Container: container (InputIterator begin, // InputIterator end of the interval); // The end of the Interval

For example:

int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };std::vector<int> myvector (myints, myints+8); 

These are common usage in c ++ 98. In C ++ 11, vector can be directly initialized:

Std: vector <int> second = {10, 20, 30, 30, 20, 10, 10, 20}; or: std :: vector <int> second ({10, 20, 30, 30, 20, 10, 10, 20 });
Insert Interval

The standard sequence container provides this form of insert:

Void container: insert (iterator position, // InputIterator begin, // InputIterator end of the insert interval); // The end Of The insert Interval

For example:

int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };std::vector<int> myvector;myvector.push_back(100);myvector.insert(myvector.begin(),myints,myints+8); //10 20 30 30 20 10 10 20 100

The associated container also supports interval insertion. However, because the inserted position is determined by its comparison function, this parameter does not exist;

Interval Deletion

Erase provided by the standard sequence container:

iterator container::erase(iterator begin, iterator end); 

The standard associated container of c ++ 98 provides the following erase:

void container::erase(iterator begin, iterator end);

After the sequence container calls erase, it returns an iterator (the next of the deleted element ),
The erase of the associated container does not return the iterator after it is deleted. [the official explanation is that if it is implemented as a sequence container, returning to the next iterator will lead to unacceptable performance degradation ];

This difference is finally unified in c ++ 11. In c ++ 11, after erase is called for the associated container, an iterator (pointing to the next element to be deleted) is returned );

iterator container::erase(const_iterator first, const_iterator last);
Interval assignment

All standard containers provide range assignment member functions:

void container::assign(InputIterator begin, InputIterator end);

This function is used to assign values to the container. It replaces the existing values and allocates space as needed;
The difference with the copy () algorithm is that it does not need to allocate space in advance and has higher performance;

int myints[]={10,20,30,40,50,60,70};std::vector<int> myvector;myvector.assign(myints,myints+7);
General interval algorithm for_each interval iteration

For_each: traverses and executes an action on each element;
C ++ 98 only supports the original for loop. Many languages (such as java and python) have implemented the foreach interval iteration syntax, which makes C ++ programmers have been jealous for a long time;
In the era of no foreach interval iteration, we can use the for_each () algorithm instead:

For example, add 5 to each element:

void myfunction (int& i) {    i += 5;}std::vector<int> myvector;myvector.push_back(10);myvector.push_back(20);myvector.push_back(30);for_each(myvector.begin(),myvector.end(),myfunction); //15 25 35

The interval iteration is added in c ++ 11, which reduces our dependency on for_each and makes it easier to use:

for(auto &i : myvector ){    i+=5;}
Save the new value of transform () after iteration to other places

After performing an operation on each element in the interval, write the modified value to the new area;
The for_each () algorithm does not modify the version of the original range;
Or in for_each:

Int addfunction (int I) {return I + 5;} void output (int I) {// output function std: cout <''<I;} std :: vector <int> myvector; myvector. push_back (10); myvector. push_back (20); myvector. push_back (30); std: vector <int> bvector; bvector. resize (myvector. size (); transform (myvector. begin (), myvector. end (), bvector. begin (), addfunction); // output for_each (bvector. begin (), bvector. end (), output); // bvector: 15 25 35
Copy () interval Replication

Interval replication is generally used for data passing between multiple containers;
This algorithm is widely used. In fact, many use cases of copy can be replaced by the range member function (this is also recommended );

For example, copy an array to vector:

int myints[]={10,20,30,40,50,60,70};std::vector<int> myvector (7);std::copy ( myints, myints+7, myvector.begin() );
Fill () interval Filling

Use one element to repeatedly fill the interval;
This algorithm is frequently used;
For example, fill in the first four elements of the vector with 5:

std::vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0std::fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 0
Replace () interval replacement

Traverse the interval and replace the values:
For example, replace all 20 in the following interval with 99:

int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };std::vector<int> myvector (myints, myints+8);            // 10 20 30 30 20 10 10 20std::replace (myvector.begin(), myvector.end(), 20, 99); // 10 99 30 30 99 10 10 99

Replace_if
For example, replace all values greater than 20 in the following interval with 99:

bool bigerThen20 (int i) { return i > 20; }int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };std::vector<int> myvector (myints, myints+8);            // 10 20 30 30 20 10 10 20std::replace_if (myvector.begin(), myvector.end(), bigerThen20, 99); //10 20 99 99 20 10 10 20

Because the imitation function is used, it is implemented through replace_if, and it is also easy to implement with for_each;

Remove () interval Deletion

Deletes a specified element from a range;

int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };std::vector<int> myvector (myints, myints+8);            // 10 20 30 30 20 10 10 20std::remove(myvector.begin(), myvector.end(), 20); // 10 30 30 10 10 ? ? ? 

Note: removing does not actually Delete elements, but just puts the elements to be deleted at the end, and returns a new tail iterator,
For example, in the preceding example, after removing is called, the value in the vector is usually // 10 30 30 10 10 10 20
To delete an element, add the member function erase () to delete it. [remove-erase usage ]:

myvector.erase(std::remove(myvector.begin(), myvector.end(), 20),myvector.end()); // 10 30 30 10 10
Unique () interval deduplication

Deleting adjacent and identical elements from a range. Similarly, this algorithm does not actually Delete elements, but moves the elements to be deleted to the end of the range;
Use [unique-erase usage ]:

int myints[] = {10,20,20,20,30,30,20,20,10};           // 10 20 20 20 30 30 20 20 10std::vector<int> myvector (myints,myints+9);std::vector<int>::iterator it;it = std::unique (myvector.begin(), myvector.end());   // 10 20 30 20 10 ?  ?  ?  ?myvector.erase(it,myvector.end());

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

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.