迭代器,lower_bound说明

本文介绍了C++中如何使用迭代器进行数组和容器的操作,并通过示例展示了如何利用lower_bound函数查找特定值的位置,同时解释了begin()、end()等函数的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在c++中封装好的stack,queue,list,vector中使用迭代器    定义 如vector<int>::iterator it;

数组用指针,已封装好的结构体用迭代器;

lower_bound采用二分搜索;

begin():返回指向容器开头的迭代器;

end():返回指向容器末尾的迭代器,这里的末尾指的是最后一个元素的下一个位置;

lower_bound(数组首地址/迭代器头,数组尾/迭代器尾,value)

distance(首地址,求出value的地址)(用于数组和vector中判断位置)

 1 #include<iostream>
 2 #include<algorithm>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int A[14] = {1 ,1, 2, 2, 2, 4, 5, 5, 6, 8, 8, 8, 10, 15 };
 9     int *pos;             //数组用指针 
10     int idx;                  
11     pos = lower_bound(A, A+14, 3); //value地址 
12     idx = distance(A, pos);        //到首地址的距离   
13     cout << "A[" <<idx<< "] = " << *pos << endl;
14     
15     pos = lower_bound(A, A+14, 2);
16     idx = distance(A, pos);
17     cout << "A[" << idx <<"] = " << *pos <<endl;
18     
19     return 0;  
20  } 

下面是用vector写,使用迭代器

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<vector>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     vector<int> A;
 9     A.push_back(1); 
10     A.push_back(2); 
11     A.push_back(3); 
12     A.push_back(4); 
13     A.push_back(5); 
14     A.push_back(6); 
15 
16     vector<int> ::iterator pos; //定义迭代器 
17     int idx;
18     pos = lower_bound(A.begin() , A.end() , 3);
19     idx = distance(A.begin() , pos);
20     cout << "A[" <<idx<< "] = " << *pos << endl;
21     
22     pos = lower_bound(A.begin()  , A.end(), 2);
23     idx = distance(A.begin() , pos);
24     cout << "A[" << idx <<"] = " << *pos <<endl;
25     
26     return 0;  
27  } 

 

转载于:https://www.cnblogs.com/Dicer/p/8532432.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值