用于存储唯一<键,值>元组的数据结构,其中<value>最小值



我必须在数据结构中存储类型的元组

<(1,1),10>
<(1,1),9>
<(2,1),5>
<(1,1),11>

我只需要

<(1,1),9>
<(2,1),5>

在c++中,哪种数据结构最适合这类问题?

这是我目前的解决方案/变通方法,我将继续寻找一个更优雅的解决方案。顺便说一句,

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <boost/unordered_map.hpp>
#include <boost/foreach.hpp>
using namespace std;

typedef pair<int, int> mapkey;
typedef boost::unordered_map<mapkey,float,boost::hash<mapkey> > hmap;
typedef hmap::iterator hitr;
class mymap
{
public:
    hmap map;
    void insert(std::pair<mapkey,float> p)
    {
        hmap::iterator i = map.find(p.first);
        if(i==map.end()){
            map.insert(p);
        }
        else{
            if(p.second<i->second){
                i->second=p.second;
            }
        }
    }
};

int main()
{

    mymap map;

    map.insert(std::make_pair(mapkey(1,1),10.0f));
    map.insert(std::make_pair(mapkey(1,2),22.0f));
    map.insert(std::make_pair(mapkey(2,1),22.0f));
    map.insert(std::make_pair(mapkey(1,1),5.0f));
        BOOST_FOREACH(hmap::value_type i, map.map) {
            mapkey m = i.first;
            std::cout <<"( "<<m.first<<" , "<< m.second<<" ) > " <<i.second<<endl;
        }
    return 0;
}

只需一个简单的HashMap即可。

具有两个属性的密钥类,假设ij

value-总是最小值,即一个简单的int

一个哈希表,带有一个自定义插入,当键以前不可见或新值小于以前的值时插入。

您可以在C++中的类中使用HashMap构建。对于您的问题,只需要简单的自定义,您只需要在HashMap中输入配对,如果

1) 密钥不存在或

2) 若键存在,则将旧值和新值进行比较,若新值小于旧值,则在HashMap中插入对。

为了便于参考,您可以在C++中使用Simple HashMap实现

最新更新