C++STL common operations prev, next articles

C++STL common operations prev, next articles


Introduction:

1.prev: reverse

2.next: displacement


We first create a set container, and put 10 numbers from 1 to 10 in the container

set<int> s;
for(int i = 1;i <= 10;++i)
    s.insert(i);

At this time, the elements in the container s are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

prev:

If the lower_bound function is used

cout<<*s.lower_bound(5)<<"\n";

Should output the first number greater than or equal to 5, here should be output 5

So what do we use prev?

cout<<*prev(s.lower_bound(5))<<"\n";

The output here is 4, which means that the initial greater than or equal becomes less than, which has a reverse effect.

next:
auto it = s.begin();
cout<<*next(it,2);

The output here is 3, which is the number in the last two positions of s.begin().

What if the parameter is negative?

it = --s.end();
cout<<*next(it,-3);

The output is the number of the first three positions, which is 7.


#include<iostream>
#include<set>
using namespace std;
int main(){
    
    
    set<int> s;
    for(int i = 1;i <= 10;++i)
        s.insert(i);
    cout<<*s.lower_bound(5)<<"\n";
    cout<<*prev(s.lower_bound(5))<<"\n";
    auto it = s.begin();
    cout<<*next(it,2)<<"\n";
    it = --s.end();
    cout<<*next(it,-3);
    return 0;
}

Insert picture description here


There are many more content of prev and next, here is a brief introduction

If you find any problems, please correct me!

Please leave a message if you don’t understand!

Guess you like

Origin blog.csdn.net/qq_45985728/article/details/115262401