具有自定义排序的C++映射中的唯一索引

Unique index in C++ map with custom sorting

本文关键字:唯一 索引 映射 C++ 自定义 排序      更新时间:2023-10-16

我有一个std::map的自定义密钥,如下所示:

struct Foo
{
    Foo(int _uid, int _priority) : unique_id(_uid), priority(_priority) {}
    bool operator<(const Foo& other) const {    
        return priority < other.priority;       
    }
    int unique_id;
    int priority;
};

我正在用这个代码创建地图:

std::map <Foo, int> bla;

这就是我插入项目的方式:

bla.insert(std::pair<Foo, int> (Foo(1,2), 3) )

这很好,排序也很好。但我的问题是,如何仅通过unique_id找到项目?find函数需要一个Foo,而这需要一个我查询时没有的priority

我更想把优先级存储在值中(而不是作为键),但我不知道如何按值排序。std::map是正确的类/模板吗?

编辑:我没有使用boost的能力,优先级也不是唯一的。

如何仅通过unique_id找到项目?

这个问题的问题是该列表包含CCD_ 7类并且按优先级排序。这使得通过CCD_ 8搜索项目成为问题。

我的建议是创建一个新的std::map

std::map <int, foo> uniqueId_To_FooClass;

并且当向bla添加新项目时,将其添加到uniqueId_To_FooClass。这样你就可以通过unique_id 找到一个foo

我更想把优先级存储在值中(而不是作为键),但我不知道如何按值排序。std::映射是否是正确的类/模板?

据我记忆所及,std::map将为您提供迭代器,该迭代器将遍历按键排序的项。按值遍历排序项并仍然使用映射的唯一方法是将整个集合重写为另一个映射,并反转键和值。

你也可以在这里查看Oli Charlesworth的答案

如果你对线性搜索很满意,那么你可以使用std::find_if:

auto it = std::find_if(bla.begin(), bla.end(), 
                       [given_id](std::pair<Foo, int> const & p)
                        {    
                            return p.first.unique_id== given_id;
                        });
if (it != bla.end() )
       //found

希望能有所帮助。

我认为std::map不是正确的选择(优先级是唯一的吗?)。我建议使用"Boost多索引容器库"(http://www.boost.org/doc/libs/1_54_0/libs/multi_index/doc/index.html)

如果您只需要搜索unique_id,就可以使用

类似于find_if,可以在struct Foo 中使用自定义==

   bool operator ==(const Foo& other) const {    
        return unique_id == other.unique_id;       
    }

然后像这个

int search_id =12;
Foo f ={search_id,6};
std::map <Foo, int>::iterator it=bla.begin();
for(;it!=bla.end();++it)
  if(it->first == f){
    std::cout<<"Found !";
    break;
  }