Try to use the interval member function to replace their single-element brothers.
- Generally, you can enter less code using the range member function.
- The interval member function makes the code clearer and more straightforward.
- When processing standard sequence containers, applying single-element member functions requires more memory allocation than completing the same purpose range member functions, copying objects more frequently, and/or causing extra operations.
// Copy an int array to the vector front endInt data [numvalues];// Assume that numvalues is defined elsewhereVector <int> V ;...// Interval member function versionV. insert (V. Begin (), data, data + numvalues );// Insert int in data into the front of V// Single-element cyclic versionVector <int>: iterator insertloc (v. begin (); For (INT I = 0; I <numvalues; ++ I) {insertloc = v. insert (insertloc, data [I]); ++ insertloc ;}
Disadvantages of Single-element loop version (for vector)
- More function calls (each cycle has an insert call)
- Move the element after more inserts (each cycle needs to move the element after each insert)
- This may cause multiple memories to be re-allocated (each allocation involves copying, constructing, and destructing objects)
- The value of insertloc should be carefully maintained for the next loop
Summary of supported range member functions:
Interval structure. All standard containers provide constructor in this form:
Container: container (inputiterator begin,// Start point of the IntervalInputiterator end );// End of the Interval
Insert interval.
- All standard sequence containers provide this form of insert:
Void container: insert (iterator position,// The insert position of the IntervalInputiterator begin,// Start point of the insert IntervalInputiterator end );// End of the insert Interval
- The associated containers use their comparison functions to determine where elements are to be placed, so they omit the position parameter.
void container::insert(lnputIterator begin, InputIterator end);
Interval deletion.
Each standard container provides an erase in the form of an interval, but the sequence and the returned type of the associated container are different. The sequence container provides the following:
iterator container::erase(iterator begin, iterator end);
The associated container provides the following:
void container::erase(iterator begin, iterator end);
Interval assignment. All standard column containers provide assign in the range format:
void container::assign(InputIterator begin, InputIterator end);
Valid STL: Use the interval member function instead of their single-element sibling function.