I have nested containers std::map<int, std::map<T, U> > and want to populate them properly, either inserting a new sub map or appending to the sub map if the integer key exists. So I came up with something like the following example:
int n = ...;
int m = ...;
obj get_some_random_obj(int i, int j); // returns some object
std::map<int, std::map<int, obj> > container; // prepopulated container
// insert some new obj's. Create a new sub map if key i is not found in container,
// append to existing sub map otherwise
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
std::map<int, std::map<int, obj> >::iterator found = container.find(i);
obj newobj = get_some_random_obj(i,j);
std::pair<int, obj> newpair(j, newobj);
if(found != container.end()) {
found->second.insert(newpair);
} else {
std::map<int, obj> newmap;
newmap.insert(newpair);
container.insert(std::make_pair(i, newmap));
}
}
}
Two questions:
- Is there a more elegant (more efficient?) way to write this?
- How can one make the above code more abstract, so that it becomes possible to populate containers with type
std::map<int, std::map<U,T>withUandTarbitrary types? I have tried to come up with a template function, but couldn’t get it to work at all.
Thank you for your help!
map’s
operator[]inserts if the element isn’t present.