简体   繁体   中英

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.

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 );

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM