【问题标题】:Find upper_bound of a String Key in STL Map在 STL 映射中查找字符串键的上限
【发布时间】:2012-10-11 15:40:29
【问题描述】:

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

我试图在 STL Map 中找到 String Key 的上限,但它没有给我确切的结果。如果你能运行这个程序,你会发现结果很奇怪,上下界都指向“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);
}

【问题讨论】:

  • 一个带有可编译源代码的问题。先生干得好!
  • @john 这是一个相当低的标准。太糟糕了,它很少值得评论。

标签: c++ map


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 2011-05-29
      • 1970-01-01
      • 2019-09-16
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多