3

在 STL Map 中查找字符串键的上限

我试图在 STL Map 中找到 String Key 的 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);
}
4

2 回答 2

4

Upper bound 为您提供了可以插入参数的最后一个位置,同时仍保持序列排序(而 lower_bound 为您提供第一个这样的位置)。由于“qw”在字典上比“qwerzzx”小,这就是该词的下限和上限。

换句话说,[lower_bound, upper_bound)是等于参数的元素的间隔 - 在这种情况下,它是空的。

如果您的意图是找到带有此前缀的最后一个单词,您可以尝试在末尾附加一些字符,以确保它在字典上大于地图中的最后一个。例如,如果您只有字母字符,您可以'z'在 ASCII 表中查找该字符并将其附加到“qw”。这样,您应该能够获得一个迭代器,在您的情况下,“xcvbqwsdfgqwerzzx”。

于 2012-10-11T15:43:25.267 回答
2

上限返回大于搜索键的项目。下界返回大于或等于的项目。在这种情况下,它们都是相同的,因为地图中没有任何东西是相同的。

目的是它们都返回一个可以在之前插入项目的位置,并且仍然保留排序顺序。lower_bound会把它放在范围的前面,然后upper_bound放在最后。

于 2012-10-11T15:43:59.103 回答