在STL Map中查找字符串键的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);
}
Run Code Online (Sandbox Code Playgroud)
Upper_bound 为您提供可以插入参数的最后一个位置,同时仍保持序列排序(而 lower_bound 为您提供第一个此类位置)。由于“qw”按字典顺序小于“qwerzzx”,因此它既是该单词的下限又是上限。
换句话说,[lower_bound, upper_bound)是等于参数的元素的间隔 - 在本例中,它为空。
如果您的目的是查找带有此前缀的最后一个单词,您可以尝试在末尾附加一些字符,以确保它按字典顺序大于地图中的最后一个单词。例如,如果只有字母字符,则可以'z'在 ASCII 表中查找紧随其后的字符并将其附加到“qw”。这样,您应该能够获得一个迭代器,在您的情况下,“xcvbqwsdfgqwerzzx”。
| 归档时间: |
|
| 查看次数: |
2422 次 |
| 最近记录: |