c ++如何查找具有最接近给定值的映射的键

时间:2017-09-18 17:45:47

标签: c++ algorithm dictionary find closest

我想找到与有序地图最接近的值的关键字。例如:

#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;
}

注释中提到的代码应该返回索引,因为所需值50比其他任何值更接近第二个位置。

有没有一种方法可以做到这一点?

PS:我知道我可以有一个“for”,搜索整个地图并在我找到一个大于给定值的值时停止,但最糟糕的执行时间是搜索整个表格。此外,我需要多次运行,所以我正在寻找比这更好的东西。

1 个答案:

答案 0 :(得分:2)

使用此容器,您只能使用线性搜索。例如,您可以使用标准算法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