2012-10-11 34 views
2
在STL地圖字符串鍵的

查找UPPER_BOUND查找字符串鍵的UPPER_BOUND在STL地圖

我試圖找到在STL地圖字符串鍵的UPPER_BOUND,但它沒有給我確切的結果。如果你可以運行這個程序,你會發現結果是奇怪的,無論是上面的&下邊界指向「qwerzzx」

我的代碼中是否有任何錯誤,或者我錯誤地解釋了上限操作..?

#include<iostream> 
#include<cstring> 
#include <map> 
using namespace std; 
int main() 
{ 
    map<string, int> testmap; 
    map<string, int>::iterator poslow; 
    map<string, int>::iterator posup; 

    testmap.insert(make_pair<string, int>("asdfghjkliopp", 1)); 
    testmap.insert(make_pair<string, int>("asdfghjklioppswert", 1)); 
    testmap.insert(make_pair<string, int>("sdertppswert", 1)); 
    testmap.insert(make_pair<string, int>("sdertppswedertyuqrt", 1)); 
    testmap.insert(make_pair<string, int>("qwerzzx", 1)); 
    testmap.insert(make_pair<string, int>("qwerzzxasdf", 1)); 
    testmap.insert(make_pair<string, int>("qwsdfgqwerzzx", 1)); 
    testmap.insert(make_pair<string, int>("xcvbqwsdfgqwerzzx", 1)); 
    testmap.insert(make_pair<string, int>("xcvbqwsdersdfgqwerzzx", 1)); 
    poslow = testmap.lower_bound("qw"); 
    posup = testmap.upper_bound("qw"); 
    cout<<"Lower POS ::: "<<poslow->first<<" UPPER POS :: "<<posup->first<<"\n"; 
    testmap.erase(poslow, posup); 
} 
+1

帶有可編譯源代碼的問題。幹得好先生! – john

+0

@john這是一個非常低的酒吧。太糟糕了,很少有值得評論的地方。 –

回答

4

上界給你的最後一個位置,你可以插入的說法,同時仍保持排序的序列(而LOWER_BOUND給你第一個這樣的位置)。由於「qw」在詞典上比「qwerzzx」小,因此這個詞的下限和上限都是。

換句話說,[lower_bound, upper_bound)是等於參數的元素的間隔 - 在這種情況下,它是空的。

如果你打算用這個前綴找到最後一個單詞,你可以嘗試在最後追加一些字符,以確保它的字典順序大於地圖上的最後一個字符。例如,如果您只有字母字符,則可以在ASCII表中將'z'後面的字符查找並將其附加到「qw」。這樣,你應該可以得到一個迭代器,在你的情況下,「xcvbqwsdfgqwerzzx」。

2

上限返回的項大於的搜索關鍵字。下限返回大於或等於的項目。在這種情況下,它們都是相同的,因爲地圖中沒有任何東西是平等的。

其意圖是他們都返回一個位置,在該位置之前可以插入項目並仍保留排序的順序。 lower_bound會把它放在範圍的前面,upper_bound會把它放在最後。