How to insert into std::map

In code below:

map<string,vector<int>> create(ifstream& in, const vector<string>& vec)
{
    /*holds string and line numbers into which each string appears*/
    typedef map<string,vector<int>> myMap;
    typedef vector<string>::const_iterator const_iter;

    myMap result;
    string tmp;
    unsigned int lineCounter = 0;

    while(std::getline(in,tmp))
    {
        const_iter beg = vec.begin();
        const_iter end = vec.end();

        while (beg < end)
        {
            if ( tmp.find(*beg) != string::npos)
            {   
                result[*beg].push_back(lineCounter);//THIS IS THE LINE I'M ASKING FOR
            }
            ++beg;
        }

        ++lineCounter;
    }

    return result;
}

How should I do it (check line commented in code) if I want to use insert method of map instead of using operator[]?
Thank you.

Upvotes: 0

Views: 2150

Answers (3)

Seriously, I would not do it.

You are only going to complicate your code unnecessarily. You would need a call to the insert to generate the new element in the map and then modify it.

Just for the sake of it (avoiding the double lookup, but building an unnecessary empty vector):

result.insert( std::make_pair( *beg, std::vector<int>() ) )
      .first->second.push_back( lineCounter );

EDIT: Real equivalent (functionality and performance):

std::map<std::string,std::vector<int> >::iterator it = result.upper_bound( *beg );
if ( it->first != *beg ) {
   it = result.insert( it, std::make_pair( *beg, std::vector<int>() ) ).first;
}
it->second.push_back( lineCounter );

Upvotes: 3

Michael Kristofik
Michael Kristofik

Reputation: 35218

map::insert returns a pair containing an iterator to the element (either the one just inserted or the existing one with that key) and a boolean indicating success or failure. You can then call iter->push_back(lineCounter) to add the new line number to the vector.

...and when you're done with all that, realize that this is exactly what operator[] does for you.

Upvotes: 1

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116306

result.insert(pair<string,vector<int>>(*beg,100), vector<int>());
result[*beg].push_back(lineCounter);

This is more complicated (but slower too :-) than your current code, since that achieves two things with a single statement: (implicitly) inserts an empty array into the map, then adds a new element to the array.

Upvotes: 1

Related Questions