在下面的代码中:
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;
}
如果我想使用 map 的 insert 方法而不是使用 operator[],我应该怎么做(检查代码中注释的行)?
谢谢。
最佳答案
说真的,我不会这样做。
您只会不必要地使您的代码复杂化。您需要调用插入以在 map 中生成新元素,然后对其进行修改。
只是为了它(避免双重查找,但构建了一个不必要的空 vector ):
result.insert( std::make_pair( *beg, std::vector<int>() ) )
.first->second.push_back( lineCounter );
编辑:真正的等价物(功能和性能):
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 );
关于c++ - 如何插入 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2712894/