C ++ 17
As mentioned in John Perry's answer , since C ++ 17 std::map provides a member function merge() . The merge() function produces the same result for the target map as the jkerian solution, using insert() , as you can see from the following example, which I borrowed from jkerian. I just updated the code with some C ++ 11 and C ++ 17 features (such as using type alias , range-based for loop with structured binding and list initialization ):
using mymap = std::map<int, int>; void printIt(const mymap& m) { for (auto const &[k, v] : m) std::cout << k << ":" << v << " "; std::cout << std::endl; } int main() { mymap foo{ {1, 11}, {2, 12}, {3, 13} }; mymap bar{ {2, 20}, {3, 30}, {4, 40} }; printIt(foo); printIt(bar); foo.merge(bar); printIt(foo); return 0; }
Exit:
1:11 2:12 3:13
2:20 3:30 4:40
1:11 2:12 3:13 4:40
As you can see, merge() also gives priority to the target map foo when the keys overlap.
However, there is a difference between using insert() and merge() respect to what happens with the original map. The insert() functions add new records to the target card, and merge() moves the records from the original card. This means that in the above example, insert() does not change bar , but merge() removes 4:40 from bar , so only 2:20 and 3:30 remain in bar .
Note: I reused an example from jkerian that uses map<int, int> for brevity, but merge() also works for your map<string, string> .
Code for Colira
honk Jun 14 '19 at 8:46 2019-06-14 08:46
source share