C++STL常用操作之prev、next篇

C++STL常用操作之prev、next篇


简介:

1.prev:反向

2.next:位移


我们先建立一个set容器,在容器中放入1-10这10个数字

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

此时容器s中的元素为1,2,3,4,5,6,7,8,9,10

prev:

如果用到lower_bound函数

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

应该输出大于等于5的第一个数,此处应该是输出5

那么我们使用prev呢?

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

这里输出的是4,也就是说刚开始的大于等于变成了小于,有着反向的效果。

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

这里输出的是3,也就是s.begin()的后两个位置的数。

如果参数是负数呢?

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

输出就是前三个位置的数了,也就是7。

扫描二维码关注公众号,回复: 12943698 查看本文章

#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;
}

在这里插入图片描述


prev和next的内容还有很多很多,这里简单介绍

发现问题欢迎指正!

有不懂请留言!

猜你喜欢

转载自blog.csdn.net/qq_45985728/article/details/115262401