tags:

views:

94

answers:

2

I have a map of a vector of char's and a vector of strings. Every so often, if I've seen the vector of characters before, I'd like to add a string to my vector of strings. Below is my code to do that.

map<vector<char>, vector<string>>::iterator myIter = mMyMap.find(vChars);
if(myIter != mMyMap.end()) {
    vector<string> vStrings = myIter->second;
    mMyMap.erase(myIter);
    vStrings.push_back(some_other_string);
    mMyMap.insert(pair<vector<char>, vector<string>>(vChars, vStrings));
    return TRUE;
}

The call to mMyMap.erase() seems to get stuck an in infinite loop though. I'm guessing it's because vStrings isn't getting a deep-copy of myIter->second.

Do I need to initalize vStrings like:

vector<string> vStrings(myIter->second);

Or what's the proper fix?

+3  A: 

I don't see an error in the posted code fragment (other than a missing )). But may I suggest simplifying lines 2-8 to:

if(myIter != mMyMap.end()) { 
    myIter->second.push_back(some_other_string); 
} 
aschepler
Something is still funky with how I was doing it, but this solves my problem so that's even better. Thanks :)
mrduclaw
A: 

vector vStrings = myIter->second;
and
vector vStrings(myIter->second);
are same things. They both call copy constructor. And the copy is deep copy only. My guess is that the vector that is getting copied is too big(or long). Each element of the vector will be copied one by one. And hence the time.

Manoj R