我已在一組使用STL容器UPPER_BOUND&LOWER_BOUND在地圖
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
地圖使用的時候,讓我錯誤的價值觀實際的代碼,當我使用設置工作:
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;
}
'映射 MYSET;'不知道如何編譯,'std :: map'包含一個鍵值對。請發佈實際的代碼示例。不要複製粘貼的東西。發佈最低限度的代碼示例,編譯並演示您的問題。 –
根據要求,編輯 – mister
這顯然不會按你所希望的那樣工作。請參閱[upper_bound](http://www.sgi.com/tech/stl/Map.html)的定義。它說:「找出第一個元素的關鍵大於k.'。 'upper_bound'也與排序結構有關。這對於不保證排序的地圖的值是無關緊要的。 – Vikas