【问题标题】:using STL Container upper_bound & lower_bound for map使用 STL 容器 upper_bound 和 lower_bound 映射
【发布时间】:2012-05-13 08:25:17
【问题描述】:

我有以下的一套

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&lt;int&gt; myset; 不确定这是如何编译的,std::map 持有一个键值对。请发布实际的代码示例。不要复制粘贴的内容。发布一个极简代码示例,它可以编译并演示您的问题。
  • 这显然不能如你所愿。参见upper_bound 的定义。它说:Finds the first element whose key greater than k.upper_bound 也与排序结构相关。它与不保证排序的地图值无关。

标签: c++ stl map upperbound


【解决方案1】:

如果您想在 map 中搜索特定值(不是键),那么您必须按顺序遍历映射并检查每个值,因为 find()lower_bound()upper_bound() 都使用键.

在发布的代码中,您可以交换valuekey,这样您就可以搜索map,因为搜索到之前的set

myset[10] = 0;
myset[20] = 2;
myset[30] = 3;
myset[40] = 4;
myset[50] = 5;
myset[60] = 6;
myset[70] = 7;

【讨论】:

  • 除了切换就没有别的办法了吗?
  • 如果您想使用map::find()map::lower_bound() 等,则不要这样做。
猜你喜欢
  • 1970-01-01
  • 2021-03-10
  • 1970-01-01
  • 2012-05-20
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
相关资源
最近更新 更多