What's the most efficient way to retrieve the added and removed elements between two structure of type:
using T = unordered_map<std::string, std::set<struct A>>;
I wrote this code.
Could you please advise?
#include <iostream>
#include <string>
#include <unordered_map>
#include <set>
#include <algorithm>
#include <ranges>
struct A {
std::string name;
std::string address;
auto operator<=>(const A& other) const = default;
};
using T = std::unordered_map<std::string, std::set<A>>;
void extractChanges(const T& t1, const T& t2, T& added, T& removed) {
for (const auto& [key, set_t2] : t2) {
const auto it_t1 = t1.find(key);
const std::set<A>& set_t1 = (it_t1 != t1.end()) ? it_t1->second : std::set<A>();
std::set<A> added_set, removed_set;
for (const auto& a : set_t2) {
if (set_t1.find(a) == set_t1.end())
added_set.insert(a);
}
for (const auto& a : set_t1) {
if (set_t2.find(a) == set_t2.end())
removed_set.insert(a);
}
if (!added_set.empty())
added.emplace(key, std::move(added_set));
if (!removed_set.empty())
removed.emplace(key, std::move(removed_set));
}
}
int main() {
T t1 = {
{"key1", {{"name1", "address1"}, {"name2", "address2"}}},
{"key2", {{"name3", "address3"}}}
};
T t2 = {
{"key1", {{"name1", "address1"}, {"name2", "address2_modified"}}},
{"key3", {{"name4", "address4"}}}
};
T added, removed;
extractChanges(t1, t2, added, removed);
return 0;
}
I want to retrieve the added and removed elements given t1 as reference and t1 as update/change.
This code handles all cases even the differences in inner sets. Is there a more efficient way to write this?