Zookeeper
Example: What is the simplest operation to make V1 content the same as the second half of V2? Let's look at the following four answers:
① V1.assign (v2.begin () + v2.size ()/2, v2.end ());
② V1.clear ();
Copy (v2.begin () + v2.size ()/2, v2.end (), back_inserter (V1 ));
③ V1.insert (v1.end (), v2.begin () + v2.size ()/2, v2.end ());
④ Vector <int> V1, V2;
...
V1.clear ();
For (vector <int>: const_iterator CI = v2.begin () + v2.size ()/2; CI! = V2.end (); ++ CI)
V1.push _ back (* CI );
⑤ Vector <int>: iteratorinsertloc (V. Begin ());
For (INT I = 0; I <numvalues; ++ I)
{
Insertloc = V. insert (insertloc, data [I]);
++ Insertloc;
}
Too many STL programmers misuse copy. By inserting an iterator to limit the copy call of the target range, almost all of them should be replaced with the call of the range member function. After the copy template is instantiated, the code based on copy is almost the same as the code using the display loop.
Method ⑤ each time insert is called to insert a new element into V, each element after the insertion point must move backward to a position to free up space for the new element. The difference is that the C ++ standard requires the interval insert function to directly move the elements in the existing container to their final location, that is, you only need to pay the price for moving each element.
There are three reasons to prioritize the selection of the range member function rather than its corresponding single-element member function:
It is easier to write range member functions.
Better express our intentions
They demonstrate higher efficiency
Supported range member functions include:
Interval creation: All standard containers provide constructors in the following form:
Container: container (inputiterator begin, inputiterator end );
Interval insertion: All standard sequence containers provide the following insert statements:
Void container: insert (iterator position, inputiterator begin, inputiteratorend );
The associated container uses the comparison function to determine where the element should be inserted. They provide a function prototype that saves the position parameter:
Void container: insert (inputiterator begin, inputiterator end );
Interval deletion: All standard containers provide interval-based deletion operations. However, the returned values of sequences and associated containers are different. The sequence container provides the following form:
Iterator container: erase (iterator begin, iterator end );
The associated container provides the following forms:
Void container: erase (iterator begin, iterator end );
Range assignment: All standard containers provide assign in the range form:
Void container: Assign (inputiterator begin, inputiterator end );