SoFunction
Updated on 2025-03-10

Summary of STL interval member functions and interval algorithms

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

Compared to single-element traversal operations, the advantages of using interval member functions are:
1) Fewer function calls
2) Less elements move
3) Less memory allocation

The interval algorithm should also be used when interval member functions are not applicable, at least, it is simpler, more effective, and less error-prone than handwriting loops;

Interval member functions

Interval structure

Standard containers all support interval constructors:

Copy the codeThe code is as follows:

container::container(InputIterator begin, // The starting point of the interval
InputIterator end); // End point of the interval

For example:

Copy the codeThe code is as follows:

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

The above is a common method in C++98. In C++11, vector can be directly initialized:

Copy the codeThe code is as follows:

std::vector<int> second ={10, 20, 30, 30, 20, 10, 10, 20}; 

or:

Copy the codeThe code is as follows:

std::vector<int> second ({10, 20, 30, 30, 20, 10, 10, 20});  

Interval insertion

Standard sequence containers provide this form of insert:

Copy the codeThe code is as follows:

void container::insert(iterator position, // The position of interval insertion
InputIterator begin, // The starting point of the insertion interval
InputIterator end); // The end point of the insertion interval

For example:

Copy the codeThe code is as follows:

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

The associative container also supports interval insertion, but since its insertion position is determined by its comparison function, there is no parameter for interval insertion position;

Interval deletion

The erase provided by the standard sequence container:

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

The standard associated container of c++98 provides an erase:

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

After the sequence container calls erase, it returns an iterator (the next one 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, it will lead to performance degradation that cannot be received];

This difference is finally unified in c++11; in c++11, after calling erase to the associated container, an iterator will be returned (pointing to the next element that was deleted);

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

Interval assignment

All standard containers provide member functions for interval assignment:

void container::assign(InputIterator begin, InputIterator end);
This function is used to assign values ​​to containers, replaces existing values, and allocates space as needed;
The difference with the copy() algorithm is that it does not require pre-allocated space and has higher performance;

Copy the codeThe code is as follows:

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

General interval algorithm

for_each interval iteration

for_each: traversal, perform an action on each element;
C++98 only supports the most primitive for loops, and many languages ​​(java, python, etc.) implement foreach interval iteration syntax, which made C++ programmers envious for a long time;
In an era without foreach interval iteration, we can use the for_each() algorithm instead:

Example: Add 5 to each element:

Copy the codeThe code is as follows:

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

New interval iterations have been added in c++11, which reduces our dependence on for_each and makes it more convenient to use:

Copy the codeThe code is as follows:

for(auto &i : myvector )
{
    i+=5;
}

transform() The new value is saved as another place after the interval iteration

After performing an operation on each element in the interval, write the modified value into the new interval;
It can be considered that this is the version of the for_each() algorithm that does not modify the original interval;
Or the example in for_each:

Copy the codeThe code is as follows:

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;
(());
transform((),(),(),addfunction);
//Output
for_each((),(),output); //bvector: 15 25 35

copy() interval copy

Interval copying is generally used to transfer data values ​​between multiple containers;
This algorithm is widely used. In fact, in many scenarios using copy, interval member functions can be used instead (it is also recommended to do so);

Example: Copy the array to vector:

Copy the codeThe code is as follows:

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

fill() interval fill

Fill the interval repeatedly with an element;
This algorithm is used less frequently;
Example: Fill the first 4 elements of vector with 5:

Copy the codeThe code is as follows:

std::vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0
std::fill ((),()+4,5);   // myvector: 5 5 5 5 0 0 0 0

replace() interval replacement

Traverse the interval and replace the value:
Example: Replace all 20 in the following interval with 99:

Copy the codeThe code is as follows:

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

More complex version (using functors) replace_if
Example: Replace all the following intervals greater than 20 with 99:

Copy the codeThe code is as follows:

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 20
std::replace_if ((), (), bigerThen20, 99); //10 20 99 99 20 10 10 20

Since functors are used, it is also easy to implement with for_each() if implemented through replace_if;

remove() interval delete

Removes the specified element from the interval;

Copy the codeThe code is as follows:

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

Note that remove does not really delete the element, but just puts the elements that need to be deleted to the end, and returns a new tail iterator.
For example, in the above example, after calling remove, the value in vector is generally //10 30 30 10 10 10 10 20
If you want to really delete the element, you need to add the member function erase() to achieve the deletion [remove-erase idiom]:

Copy the codeThe code is as follows:

(std::remove((), (), 20),()); // 10 30 30 10 10

unique() interval deduplication

Delete adjacent identical elements from the interval. Similarly, this algorithm will not really delete elements, but will move the elements to be deleted to the end of the interval;
Use [unique-erase idiom]:

Copy the codeThe code is as follows:

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

The above is the entire content of this article, I hope you like it.