c++ - 在 cpp 中设置的下限
问题描述
要找到向量中元素的索引,我们通常会找到
it=lower_bound(vector.begin(),vector.end(),element)
并像这样减去它int index = it-vector.begin()
但是相同的概念不适用于设置为什么以及如何做到这一点?因为int pos = it-a.begin()
在下面的程序中给了我错误。
我想在该元素的集合中找到元素的位置。
#include<bits/stdc++.h>
using namespace std;
set<int>a;
int main(){
int n,m,k;
cin>>n>>m>>k;
for(int i=1;i<=k;i++){
int u;
cin>>u;
a.insert(u);
}
int ans=0;
while(n--){
for(int i=0;i<m;i++){
int u;
cin>>u;
set<int>::iterator it = a.lower_bound(u);
int pos = it-a.begin();
a.erase(it);
a.insert(a.begin(),u);
ans+=pos;
}
}
cout<<ans;
}
解决方案
您不能完全将通用算法std::lower_bound()
与std::set
迭代器一起使用,原因与您无法计算距离的原因相同it2 - it1
- 这需要随机访问迭代器并且std::set
不提供它们。您可以改用std::set::lower_bound()
它std::distance( it1, it2 )
来计算差异,但您需要注意非随机访问迭代器的成本会更高。因此,您的代码可以通过以下方式修复:
int pos = std::distance( a.begin(), it );
请注意,结果std::distance()
可能不适合int
(虽然计算距离的问题相同it2 - it1
)。
注意:您可能更喜欢使用std::distance()
而不是从另一个迭代器中减去一个迭代器,因为它在随机访问时会很有效,并且仍然可以在前向迭代器上工作,尽管成本更高。
注意2:在std::set
通常指向错误设计的位置。您要么使用错误的数据结构,要么使用错误的方法。
推荐阅读
- python - 在二维 numpy 数组中查找最常见的字符串
- python - 是否可以将数据帧传递给每行都有一个 numpy 数组的 TF/Keras?
- python - 如何从python中的df中减去(最后一列,最后一行)减去(最后一列,第一行)
- graphdb - FROM 关键字不检索远程三元组
- javascript - 使用下拉内容中单击选项的值更改 dropbtn 文本
- angular - Angular - 找不到模块“ngx-thread”
- python - 无法安装pocketsphinx
- c# - DataGrid向单元格按钮添加功能
- java - 如何编写一个 do while 循环以要求用户输入数字并在输入的数字为 0 时终止循环
- javascript - 尽管为 keydown(或 keyup)函数使用了数组,但我的代码仍然拒绝让我在跳跃时移动