最近由于工作需要,需要使用一致性hash算法,其中要根据对象的hash查找应该落到的虚拟节点,由于对象的hash值一般跟 key不等,要查找大于等于key的第一个值,平时使用map 这两个用的少,刚开始就没想到,后来无意中找到这两个函数,感觉应该可以满足我的需求,但是函数的具体意思没看太懂,还是自己写个例子 看下吧;
先看下http://www.cplusplus.com/reference/map/map/upper_bound/中的解释
std::map::upper_bound
iterator upper_bound (const key_type& k); const_iterator upper_bound (const key_type& k) const;
Return iterator to upper bound
Returns an iterator pointing to the first element in the container whose key is considered to go after
k.
The function uses its internal comparison object ( key_comp) to determine this, returning an iterator to the first element for which key_comp(k,element_key) would return true.
If the map class is instantiated with the default comparison type ( less), the function returns an iterator to the first element whose key is greater than k.
A similar member function, lower_bound, has the same behavior as upper_bound, except in the case that the map contains an element with a key equivalent to k: In this case lower_bound returns an iterator pointing to that element, whereas upper_bound returns an iterator pointing to the next element.
upper_bound返回值是一个指向容器中第一个元素的迭代器,该容器中的元素满足在k的后面,(返回元素的key>k)
std::map::lower_bound
iterator lower_bound (const key_type& k); const_iterator lower_bound (const key_type& k) const;
Return iterator to lower bound
Returns an iterator pointing to the first element in the container whose key is not considered to go before
k (i.e., either it is equivalent or goes after).
The function uses its internal comparison object ( key_comp) to determine this, returning an iterator to the first element for which key_comp(element_key,k) would return false.
If the map class is instantiated with the default comparison type ( less), the function returns an iterator to the first element whose key is not less than k.
lower_bound 返回值是
是一个指向容器中第一个元素的迭代器,该容器中的元素满足不在k的前面,(返回元素的key>=k)
#include "stdafx.h"
#include <string>
#include <map>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
map<int,string> maptmp;
map<int,string>::iterator pos,pos1;
maptmp[1]="a";
maptmp[2]="b";
maptmp[4]="c";
maptmp[3]="f";
maptmp[5]="d";
pos = maptmp.lower_bound(3);
pos1 = maptmp.upper_bound(3);
printf("lower_bound %d=>%s\n",pos->first,pos->second.c_str());
printf("upper_bound %d=>%s\n",pos1->first,pos1->second.c_str());
system("pause");
return 0;
}
#include "stdafx.h"
#include <string>
#include <map>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
map<int,string> maptmp;
map<int,string>::iterator pos,pos1;
maptmp[1]="a";
maptmp[2]="b";
maptmp[4]="c";
// maptmp[3]="f";
maptmp[5]="d";
pos = maptmp.lower_bound(3);
pos1 = maptmp.upper_bound(3);
printf("lower_bound %d=>%s\n",pos->first,pos->second.c_str());
printf("upper_bound %d=>%s\n",pos1->first,pos1->second.c_str());
system("pause");
return 0;
}
查找的key=3的元素不存在,则两个函数返回都是key=4的迭代器