具有自定义排序的C++映射中的唯一索引
Unique index in C++ map with custom sorting
我有一个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;
}
- 数组索引的值没有增加
- 何时在引用或唯一指针上使用移动语义
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 计算排序向量的向量中唯一值的计数
- 查找最接近的大于当前数字的数字的索引
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 队列验证层错误:队列族索引在 pCreateInfo->pQueueCreateInfos 数组中不是唯一的
- 找到唯一向量的索引和逆映射
- 如何添加multi_index_container中指定的有序唯一索引
- 增强对哈希唯一索引的多索引访问
- 具有自定义排序的C++映射中的唯一索引
- 具有唯一元素和按索引访问的容器
- MISRA C++-2008规则5-0-15-数组索引应是指针算术的唯一形式
- 检查几个组合框的索引是否唯一