c++ - 如何插入 std::map

标签 c++ dictionary

在下面的代码中:

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/

相关文章:

database - 如何使用 sed 使用引用文件在文件中进行数千次替换?

java - 在 Java 中迭代 Map<TypeA,Set<Type>> 并将其转换为 Map<Type B,Set<TypeA>>

python - 用字符串在字典中找到最近的键?

c++ - 我可以只使用固定数组而不是内存池吗?

python - c++中的这些python函数?

c++ - boost.mpi 中的自定义 reduce 操作

c++ - 有人用过smartwin(一个Windows C++ GUI OS库)吗?

c++ - 如何在不对其施加力的情况下旋转 Box2D 主体?

python - 为什么我不能调用 del [ :] on a dict?

python numpy array/dict 多重继承