Inserting into a vector which is in a map?

I have a program that stores values in a map>. I use the map as a dictionary so that I can look through my map if a perticular string already exists. If a string does exist, I want to put the position that I found it at (relative to my text file) in my vector. How do I do this? So far I've tried this:

1
2
3
4
5
6
7
8
9
10
11
12
void mapInsert(string aWordNoSpaces, int index){
    // check if word exists in map already, but first we need an iterator object
    map<string,vector<unsigned int>>::iterator it;
    it = wordMap.find(aWordNoSpaces);

    if(it == wordMap.end()){
        wordMap.insert(pair<string,vector<unsigned int>>(aWordNoSpaces,index));
    }
    else{
        it->second.push_back(index);
    }
}


Also, why are the zeros showing up here (i've attached a screenshot and circled them): http://i.imgur.com/z1YIG83.jpg
With the subscript operator, an empty vector would be created if the key does not exist.

1
2
3
4
void mapInsert( string aWordNoSpaces, int index )
{ 
    wordMap[aWordNoSpaces].push_back(index) ;
}
As mentioned in the other thread (Btw, don't start a new thread for the same subject), there is no need to use the find function on the map, the insert function returns an iterator to the relevant item, if is already there. You can use this to push_back the word's position into the vector.

Because the insert function does a find internally, doing your own find as well will ruin the efficiency.

Hope all goes well - I look forward to see how you are going. Cheers
> there is no need to use the find function on the map,
> the insert function returns an iterator to the relevant item...

There is no need to use the insert function either; unless one fancies writing convoluted code.
@JLBorges

OK, I can see your way is better & easier.
@JLBorges

Thank you!! This solved exactly what I was trying to figure out and actually improved my implementation by a lot!
Topic archived. No new replies allowed.