使用 STL Container upper_bound & lower_bound for map
using STL Container upper_bound & lower_bound for map
我有以下一组
set<int> myset;
set<int>::iterator it,itlow,itup;
for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90
itup=myset.upper_bound (50); //
cout << "upper_bound at position " << (*itup) << endl;
//output: 60
如何为地图执行此操作? 我认为下面的程序似乎正在使用地图的第一个值而不是第二个值,因此我收到错误。
如何将其设置为使用第二个值?
map<int,int> myset;
map<int,int>::iterator it,itlow,itup;
for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90
itup=myset.upper_bound (50); //
cout << "upper_bound at position " << (*itup).second << endl;
//output: some random value returns
与map一起使用时给我错误值的实际代码,当我使用set时有效:
int x = 50;
map<int,int> myset;
//for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90
myset[0] = 10;
myset[2] = 20;
myset[3] = 30;
myset[4] = 40;
myset[5] = 50;
myset[6] = 60;
myset[7] = 70;
map<int,int>::iterator begin,upbound,lobound,it;
map<int,int>::reverse_iterator end;
end = myset.rbegin();
begin = myset.begin();
upbound=myset.upper_bound(x);
lobound=myset.lower_bound(x);
lobound--;
if(myset.size()==1)
{
cout << "upper_range = " << x <<endl;
cout << "lower_range = " << x <<endl;
}
else if(x == (*begin).second)
{
cout << "upper_range = " << (*upbound).second <<endl;
cout << "lower_range = " << end->second <<endl;
}
else if(x == end->second)
{
cout << "upper_range = " << (*begin).second <<endl;
cout << "lower_range = " << (*lobound).second <<endl;
}
else
{
cout << "start = " << (*begin).second <<endl;
cout << "end = " << end->second<<endl;
cout << "upper_range = " << (*upbound).second <<endl;
cout << "lower_range = " << (*lobound).second <<endl;
}
如果要在map
中搜索特定值(不是键),则必须按顺序遍历映射并检查每个值,如find()
、lower_bound()
,upper_bound()
都使用该键。
在发布的代码中,您可以交换value
和key
,这将允许您在搜索前一个set
时搜索map
:
myset[10] = 0;
myset[20] = 2;
myset[30] = 3;
myset[40] = 4;
myset[50] = 5;
myset[60] = 6;
myset[70] = 7;
相关文章:
- 空集"Out of bound iterator"
- 将张量的"lower diagonal"映射到矩阵,作为将矩阵的下三角形部分提取到向量的推广
- 为什么<<低;和 cout<<v.begin;单独给出错误,但 cout <<(lower.begin());没有给出任何错误,并使代码易于编译
- 使用多个文件时"array bound is not an integer constant before ']' token"
- "A reference may be bound only to an object",为什么"const int &ref = 3;"有效?
- 如何修复"reference cannot be bound to dereferenced null pointer"警告
- 当你有一个像 ::lower 这样的参数时,这在C++中是什么意思
- GCC 检测"subindex out of bound"错误
- 如果我没有得到分段错误,如何找到"index out of bound"
- 一个程序将字符串Upper char更改为Lower char得到错误
- std:: lower的行为在不同的语言环境中是如何变化的?
- 在main中声明Array之前,Array bound不是整型常量
- 获取错误"array bound is not an integer constant before ']' token"
- 如何在C或c++中获得与Java中的toLowerCase或Python中的string.lower()相同的结果
- 在运行时创建结构时"array bound is not an integer constant"