c ++如何找到具有给定值最接近值的映射的键
c++ how to find the key of a map that has the closest value of a given value
我想找到与排序映射最接近值的键。例如:
#include <iostream>
#include <map>
int main ()
{
std::map<int,int> mymap;
mymap[1]=10;
mymap[2]=40;
mymap[3]=100;
mymap[4]=200;
mymap[5]=500;
int wantedvalue=50;
int wantedindex=mymap.whatshouldIdohere(wantedvalue);
std::cout<<"The closest value of "<<wantedvalue<<" in the map is located";
std::cout<<" on "<<wantedindex<<" and is "<<mymap[wantedindex]<<std::endl;
//Should be:
//The closest value of 50 in the map is located on 2 and is 40
return 0;
}
评论中提到的代码应该 return 索引,因为想要的值 50 比任何其他值都更接近第二个位置。
有什么方法可以做到这一点吗?
PS:我知道我可以 "for",搜索整个地图并在发现大于给定值的值时停止,但最糟糕的执行时间是搜索整个地图table。我还需要 运行 这么多次,所以我正在寻找比这更好的东西。
使用此容器,您只能使用线性搜索。例如,您可以使用标准算法 std::min_element
。否则你应该使用另一个容器。
给你
#include <iostream>
#include <map>
int main()
{
std::map<int, int> mymap;
mymap[1] = 10;
mymap[2] = 40;
mymap[3] = 100;
mymap[4] = 200;
mymap[5] = 500;
int wantedvalue = 50;
auto it = std::min_element( mymap.begin(), mymap.end(),
[&](const auto &p1, const auto &p2)
{
return
std::abs(( long )p1.second - wantedvalue) <
std::abs(( long )p2.second - wantedvalue);
});
std::cout << "The closest value of " << wantedvalue << " in the map is located";
std::cout << " on " << it->first << " and is " << it->second << std::endl;
return 0;
}
程序输出为
The closest value of 50 in the map is located on 2 and is 40
我想找到与排序映射最接近值的键。例如:
#include <iostream>
#include <map>
int main ()
{
std::map<int,int> mymap;
mymap[1]=10;
mymap[2]=40;
mymap[3]=100;
mymap[4]=200;
mymap[5]=500;
int wantedvalue=50;
int wantedindex=mymap.whatshouldIdohere(wantedvalue);
std::cout<<"The closest value of "<<wantedvalue<<" in the map is located";
std::cout<<" on "<<wantedindex<<" and is "<<mymap[wantedindex]<<std::endl;
//Should be:
//The closest value of 50 in the map is located on 2 and is 40
return 0;
}
评论中提到的代码应该 return 索引,因为想要的值 50 比任何其他值都更接近第二个位置。
有什么方法可以做到这一点吗?
PS:我知道我可以 "for",搜索整个地图并在发现大于给定值的值时停止,但最糟糕的执行时间是搜索整个地图table。我还需要 运行 这么多次,所以我正在寻找比这更好的东西。
使用此容器,您只能使用线性搜索。例如,您可以使用标准算法 std::min_element
。否则你应该使用另一个容器。
给你
#include <iostream>
#include <map>
int main()
{
std::map<int, int> mymap;
mymap[1] = 10;
mymap[2] = 40;
mymap[3] = 100;
mymap[4] = 200;
mymap[5] = 500;
int wantedvalue = 50;
auto it = std::min_element( mymap.begin(), mymap.end(),
[&](const auto &p1, const auto &p2)
{
return
std::abs(( long )p1.second - wantedvalue) <
std::abs(( long )p2.second - wantedvalue);
});
std::cout << "The closest value of " << wantedvalue << " in the map is located";
std::cout << " on " << it->first << " and is " << it->second << std::endl;
return 0;
}
程序输出为
The closest value of 50 in the map is located on 2 and is 40