Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在std::map中搜索限制搜索值的键_C++_Stdmap - Fatal编程技术网

C++ 在std::map中搜索限制搜索值的键

C++ 在std::map中搜索限制搜索值的键,c++,stdmap,C++,Stdmap,假设我有std::map,map中的键是两个整数值对 是否可以找到一个限制我要查找的值的键 例如:如果地图包含: key = {4, 9} 基于x大于4且x小于9,我可以找到此键吗?其中x是某个整数值 我希望它有意义。您可以使用std::find\u if算法。退房 #包括 #包括 #包括 #包括 int main(){ 映射m{{{1,3},4},{{6,10},5},{{123,126},111}; int x=8; 自动结果=std::find_if(std::begin(m),std:

假设我有
std::map
,map中的键是两个整数值对

是否可以找到一个限制我要查找的值的键

例如:如果地图包含:

key = {4, 9}
基于
x
大于4且
x
小于9,我可以找到此键吗?其中
x
是某个整数值


我希望它有意义。

您可以使用std::find\u if算法。退房

#包括
#包括
#包括
#包括
int main(){
映射m{{{1,3},4},{{6,10},5},{{123,126},111};
int x=8;
自动结果=std::find_if(std::begin(m),std::end(m),[x](const auto&v){
返回v.first.first
但是,根据您的具体目标,您的问题有两种备选解决方案:

1) 使用相等的_范围() 将为您提供由两个迭代器定义的范围。第一个迭代器指向不小于key的元素,第二个迭代器指向大于key的第一个元素

因此,如果您要查找与某个精确关键点相关的边界,那么它可能就是您要查找的:

auto r2 = m.equal_range ({1,2});
if (r2.first!=m.end()) {
    std::cout<<"Found range1 -> "<< r2.first->second << std::endl;
}
if (r2.second!=m.end()) {
    std::cout<<"Found range2 -> "<< r2.second->second << std::endl;
}
//attention the r2.first==r2.second if exact value not found. 
autor2=m.equal_范围({1,2});
if(r2.first!=m.end()){

std::cout如果间隔不重叠,您可以这样做:

std::映射地图;
好在现在比较是透明的,所以我们可以设计自己的类型,为我们做正确的事情:

struct target
{
    int value;
};
constexpr bool operator<(target a, std::pair<int, int> b) noexcept {
    return a.value <= b.first;
}
constexpr bool operator<(std::pair<int, int> a, target b) noexcept {
    return a.second <= b.value;
}

themap.find(target{value});
struct目标
{
int值;
};

constexpr bool operator不迭代映射。检查
lower_bound()-1
?如果您的键中有重叠的区域怎么办?您可以有两个不同的区域,其中包含在地图中不相邻的值
x
。我不清楚您在问什么。我建议发布一个,在地图上迭代,找出您要找的内容。SO的某人可能知道更好的方法。@1201ProgramAlarm:没有重叠的范围。
auto r3 = m.equal_range ({x,0});
for (auto r=r3.first; r!=m.end() && r->first.first==x; r++) {
    std::cout<<"In range -> "<< r->second << std::endl;
}
std::cout<<"That's all I found for <<x<<std::endl;
auto r3 = m.find (x);   // look for first component
if (r3==m.end()) 
    std::cout<<"r3 not found"<<std::endl; 
else for (auto r : r3->second) {  // iterate on second component
    std::cout<<"In range -> "<< r.second << std::endl;
}
std::map<std::pair<int, int>, int, std::less<>> themap;
struct target
{
    int value;
};
constexpr bool operator<(target a, std::pair<int, int> b) noexcept {
    return a.value <= b.first;
}
constexpr bool operator<(std::pair<int, int> a, target b) noexcept {
    return a.second <= b.value;
}

themap.find(target{value});