How to maintain vector of map pointers in C++
I did search for similar posts in StackOverFlow and understood that it is tricky to do. Here is the problem i am facing.
I wrote a function which has takes vector of maps (vector<map<char, char> >
) and updates them. As it updates the contents, I need to send it as vector<map<char, char>* >*
Suppose I wanted to search this data structure to see whether there is any mapping of character I am looking for. I did this
vector<map<char, char>* >::iterator it = my_ds->begin();
for (; it != my_ds->end(); ++it) {
map<char, char>::iterator map_it = (*it).find(given_char);
if (map_it != (*it).end()) {
// Found
}
}
// Update the map. With some condition either I update existing map or create a newmap.
if (update_existing_map) {
map<char, char>* my_map = my_ds[update_index];
my_map->insert(pair<char, char>(given_char, required_char));
}
else {
map<char, char> my_map;
my_map.insert(pair<char, char> (given_c开发者_开发技巧har, required_char));
my_ds.push_back(&my_map); // This might be a problem
}
}
Now this program hangs after a while, when I search online about it, People told that its because when vector doubles its size, it has lot of invalid pointers, so it might enter in to infinite loop in chasing these invalid pointers.
What I should do to make it work?
map<char, char> my_map;
my_map.insert(pair<char, char> (given_char, required_char));
my_ds.push_back(&my_map); // This might be a problem
You're right - that's a problem. You're pushing the address of a local variable. You could instead do:
map<char, char> *my_map = new map<char, char>;
my_map->insert(pair<char, char> (given_char, required_char));
my_ds.push_back(my_map);
Re-sizing the vector won't create invalid pointers - the vector will keep the pointers you are storing correctly. If you keep the addresses of any of the items in the vector though (not your stored pointers) they may change, and adding to the vector will invalidate any iterators you have.
精彩评论