繁体   English   中英

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

[英]Find upper_bound of a String Key in STL Map

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

我正在尝试在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);
}

上限为您提供了最后一个可以插入参数的位置,同时仍使序列保持排序(而lower_bound则为您提供了第一个此类位置)。 由于“ qw”在字典上比“ qwerzzx”小,因此该词的上下边界均相同。

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

如果您打算查找带有该前缀的最后一个单词,则可以尝试在末尾附加一些字符,以确保它在字典上比地图中的最后一个大。 例如,如果只有字母字符,则可以在ASCII表中的'z'之后查找字符,并将其附加到“ qw”。 这样,您应该可以得到一个迭代器,以“ xcvbqwsdfgqwerzzx”为例。

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

目的是使两者都返回一个位置,在该位置可以将项目插入到该位置,并仍然保留已排序的顺序。 lower_bound会将其放在范围的前面,而upper_bound会将其放在范围的结尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM