[英]Inserting into a std::Multimap of std::Map (C++)
If I have a std::multimap<int, std::map<int, MyClass>> myMultimap
how to I insert a class object MyClassA
into the map with value 1
at multimap value 2
? 如果我有一个
std::multimap<int, std::map<int, MyClass>> myMultimap
如何我插入一个类对象MyClassA
与值地图1
在多重映射值2
?
It looks like I can do myMultimap.at(2).insert(std::pair<1,MyClassA>);
看起来我可以做
myMultimap.at(2).insert(std::pair<1,MyClassA>);
in c++11 but I am using c++98 due to a library regression/incomparability out of my control. 在c ++ 11中,但是由于库的回归/不可比性,我无法使用c ++ 98。
I've also tried 我也尝试过
myMultimap[2].insert(
std::make_pair(
myMultimap[2].end(),
myClassA
)
);
which gives: error: no match for 'operator[]' (operand types are 'std::multimap<int, std::map<int, ns_namespace::MyClassType> >' and 'int')|
给出:
error: no match for 'operator[]' (operand types are 'std::multimap<int, std::map<int, ns_namespace::MyClassType> >' and 'int')|
for both of the [
... ]
's. 两个
[
... ]
的。
I don't want to do something like myMultimap.insert(std::make_pair(2,std::make_pair(1,MyClassA)))
because if I understand correctly, this would make a new map in the multimap rather than assigning the class object to the existing map within the multimap. 我不想做类似
myMultimap.insert(std::make_pair(2,std::make_pair(1,MyClassA)))
类的myMultimap.insert(std::make_pair(2,std::make_pair(1,MyClassA)))
因为如果我正确理解,这将在多图上创建一个新图,而不是分配多重地图中现有地图的class对象。
It is a two stage process: 这是一个两个阶段的过程:
I don't know why the outer map us a multimap (they are rarely useful) so the exampke just uses the first entry: 我不知道为什么外面的地图会给我们一个多重地图(它们很少有用),所以示例仅使用第一个条目:
auto it = mymultimap.lower_bound(2);
if (it == mymultimap.end() || it->first != 2) {
it = mymultimap.insert(
std::make_pair(2, std::map<int, MyClass>())).first;
}
(*it)[1] = MyClassA;
(typed on a mobile device: there are probably typos but the overall approach should work). (在移动设备上键入:可能有错别字,但整体方法应该可行)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.