在 STL 映射中查找字符串键upper_bound

Find upper_bound of a String Key in STL Map

本文关键字:upper bound 字符串 查找 STL 映射      更新时间:2023-10-16

在 STL 映射中查找字符串键upper_bound

我试图在 STL Map 中找到字符串键的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);
}

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

换句话说,[lower_bound, upper_bound)是等于参数的元素的区间 - 在本例中,它是空的。

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

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

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