2012-10-11 32 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会把它放在最后。