int* it = lower_bound(a, a + n, q);
时间: 2024-03-15 11:42:31 浏览: 16
这段代码使用了STL中的lower_bound函数,它的作用是在一个已经排好序的数组a中查找第一个大于或等于q的元素,并返回该元素的指针。在这段代码中,a是指向数组首元素的指针,n是数组的长度,q是要查找的值。函数返回的指针it可以用来访问数组中的元素,或者用来计算该元素在数组中的索引。需要注意的是,如果数组中没有大于或等于q的元素,则函数返回指向数组最后一个元素之后的位置的指针。
相关问题
int p=lower_bound(all(q), tmp) - q.begin();什么意思
这行代码中使用了 STL 的 lower_bound 函数,它的作用是在一个有序序列中查找第一个大于或等于给定值的元素的位置。其中,all(q) 表示将容器 q 中的所有元素作为参数传递给 lower_bound 函数,q.begin() 返回容器 q 的起始迭代器,-q.begin() 的结果是一个整数,表示 tmp 在序列中的位置。因此,整个表达式的结果是 tmp 在序列 q 中的下标位置,赋值给变量 p。注意,lower_bound 函数的前提条件是序列已经按照从小到大的顺序排好。
#include <iostream> #include <string> #include <vector> #include <algorithm> #include<list> #include<queue> using namespace std; int main() { int n,m; int a[1000]; int i; while(cin>>n>>m) { for(i=0;i<n;i++) { cin>>a[i]; } std::sort(a,a+n); for(int j=0;j<m;j++) { int b; cin>>b; int*it=std::lower_bound(a,a+n,b); if (it != a + n && *it == b) { std::cout<<b<<" found at "<<it-a+1<<endl; } else { std::cout<<b<<" not found"<<endl; } }} return 0; }怎么修改可以让运行时不需要另外输回车键继续
你可以在输入完 `n` 和 `m` 后,使用 `cin.ignore()` 来清除输入缓冲区中的换行符,使程序可以直接继续读取下一个输入。修改后的代码如下所示:
```c++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <list>
#include <queue>
using namespace std;
int main() {
int n, m;
int a[1000];
int i;
while (cin >> n >> m) {
for (i = 0; i < n; i++) {
cin >> a[i];
}
std::sort(a, a + n);
for (int j = 0; j < m; j++) {
int b;
cin >> b;
int* it = std::lower_bound(a, a + n, b);
if (it != a + n && *it == b) {
std::cout << b << " found at " << it - a + 1 << endl;
} else {
std::cout << b << " not found" << endl;
}
}
cin.ignore(); // 清除输入缓冲区中的换行符
}
return 0;
}
```
这样,程序就可以连续读取多组输入了,而不需要再输入回车键继续。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)