C++ 获取堆叠贴图中的值
我有一张堆叠的地图,看起来像这样:C++ 获取堆叠贴图中的值,c++,C++,我有一张堆叠的地图,看起来像这样: std::multimap m 我如何指出TypeA的值?我试过: TypeA t = m.second.second 或指针: for (std::multimap <double, std::map<int,StopID>>::iterator p = m.begin(); p != m.end(); p ++ ){ .... TypeA t = p->second->second } 有什么想法吗?m->se
std::multimap m
我如何指出TypeA的值?我试过:
TypeA t = m.second.second
或指针:
for (std::multimap <double, std::map<int,StopID>>::iterator p = m.begin(); p != m.end(); p ++ ){
....
TypeA t = p->second->second
}
有什么想法吗?
m->second
是一个std::map
对象。必须为下一个贴图使用循环:
using multimap_t = std::multimap <double, std::map<int, TypeA>>;
for (multimap_t::iterator p = m.begin(); p != m.end(); p++) {
std::map<int, TypeA>>& map = p->second;
for (decltype(p->second)::iterator miter = map.begin(); miter != map.end(); ++miter) {
TypeA t = miter->second;
// ...
}
}
编辑:如果我正确理解注释,
map
始终只包含一个int,TypeA
对-在这种情况下,只需将map
替换为std::pair
,您只能有一个循环:
#include <utility> // std::pair
int main() {
std::multimap <double, std::pair<int, TypeA>> m;
for(auto& [the_double, the_pair] : m) {
auto& [the_int, the_type_a] = the_pair;
// do what you want with the int and TypeA references
}
}
\include//std::pair
int main(){
std::多重映射m;
对于(自动和[双精度,双精度对]:m){
自动&[the_int,the_type_a]=该对;
//对int和TypeA引用执行所需操作
}
}
澄清:您想从map
中检索特定的TypeA
?p->second
类型为map
。如何从映射中检索元素?因此for循环的时间复杂度为O(n),因为第二个循环有1个元素?是的。假设每个std::map
都有一个元素:@HaAnTran,与接受的答案中使用的两个循环完全相同。为什么地图总是只有一个元素?听起来像是std::pair
会更好。我添加了一个例子。@HaAnTran我不确定我是否理解。带有一个元素的映射
按升序和降序进行排序。还有一个std::pair
。可以这么说,没有什么可分类的如您所见,排序是在multimap
键上完成的,因为map
只有一个元素,所以有什么可以排序?@HaAnTran没有示例@godbolt-但是如何使用map
而不是对来解决multimap中的排序问题?没有。必须按所需顺序插入具有相等键的元素。也许您也不应该使用multimap
。如果您使用一个普通的向量
并放置一个结构{double d;int i;TypeA ta;}代码>在其中,排序将很容易。@HaAnTran在*集合中,所有成员都可以参与排序。没有从键到值的映射。您只有一组实体,并自行决定如何对它们进行排序。
for (auto p = m.begin(); p != m.end(); p++) {
auto& map = p->second;
for (auto miter = map.begin(); miter != map.end(); ++miter) {
TypeA t = miter->second;
// ...
}
}
for (std::multimap <double, std::map<int,StopID>>::iterator p = m.begin(); p != m.end(); p ++ ){
for(auto& [the_double, the_map] : m) {
for(auto& [the_int, the_type_a] : the_map) {
// do what you want with the TypeA reference "the_type_a"
}
}
#include <utility> // std::pair
int main() {
std::multimap <double, std::pair<int, TypeA>> m;
for(auto& [the_double, the_pair] : m) {
auto& [the_int, the_type_a] = the_pair;
// do what you want with the int and TypeA references
}
}