我有两个QVariantMap
实例A和B。
在A中,我有以下字符串:[ "key1" => "Cat", "key2" => "Dog", "key3" => "Mouse" ]
。在B中,我有以下字符串:[ "key1" => "Cat", "key4" => "Dog", "key3" => "Bison" ]
。
我想将它们合并到第三个QVariantMap
实例C中,以便它包含以下内容:
[ "key1" => "Cat", "key2" => "Dog", "key3" => "Bison", "key4" => "Dog" ]
。
注意如何只有一只"猫",以及"老鼠"是如何被"野牛"取代的。
有没有一种方法可以在Qt5中做到这一点,而无需编写自己的实用程序函数?
QVariantMap A;
QVariantMap B;
QVariantMap C;
A.insert("key1", "Cat");
A.insert("key2", "Dog");
A.insert("key3", "Mouse");
B.insert("key1", "Cat");
B.insert("key4", "Dog");
B.insert("key3", "Bison");
//Merge A and B
C = A.unite(B);
//C.value("key1") = "Cat"
//C.value("key3") = "Bison"
//C.values("key3") = {"Bison", "Mouse"}
//C.values("key1") = {"Cat", "Cat"}
//Note: A = C as well. If you don't want to change the value of A, then assign a temporary value to A or create a copy of A
//Method 1: Create a copy of A
QVariantMap ACopy = A;
C = ACopy.unite(B);
//Method 2: Create a temporary variable that hold A value:
QVariantMap ATemp = A;
C = A.unite(B);
A = ATemp;
自5.15以来,Qt提供了一个以另一个QMap
为参数的insert
重载,它将其他映射中的所有键/值对插入到原始映射中,覆盖现有键:
QVariantMap A;
QVariantMap B;
A.insert("key1", "Cat");
A.insert("key2", "Dog");
A.insert("key3", "Mouse");
B.insert("key1", "Cat");
B.insert("key4", "Dog");
B.insert("key3", "Bison");
QVariantMap C(A);
C.insert(B);
// C now holds the combined keys&values of A & B;
// for keys existing in both A and B, the values from B are taken!
QVarianMap C(A); // copy-construct C from A
for (auto i = B.constBegin(); i != B.constEnd(); ++i)
{
C.insert(i.key(), i.value()); // add B's element to C replacing C's entry with the same key if such exists
}