如何在C ++中创建从映射到映射的倒排索引?

时间:2012-06-15 00:42:51

标签: c++ map indexing

我正在尝试从地图创建地图中的倒排索引。此刻我有了这段代码:

int main()
{

    char lineBuffer[200];
    typedef std::map<std::string, int> MapType;
    std::ifstream archiveInputStream("./hola");

    // map words to their text-frequency
    std::map<std::string, int> wordcounts;

    // read the whole archive...
    while (!archiveInputStream.eof())
    {
        //... line by line
        archiveInputStream.getline(lineBuffer, sizeof(lineBuffer));

        char* currentToken = strtok(lineBuffer, " ");

        // if there's a token...
        while (currentToken != NULL)
        {
            // ... check if there's already an element in wordcounts to be updated ...
            MapType::iterator iter = wordcounts.find(currentToken);
            if (iter != wordcounts.end())
            {
                // ... then update wordcount
                ++wordcounts[currentToken];
            }
            else
            {
                // ... or begin with a new wordcount
                wordcounts.insert(
                        std::pair<std::string, int>(currentToken, 1));
            }
            currentToken = strtok(NULL, " "); // continue with next token
        }

        // display the content
        for (MapType::const_iterator it = wordcounts.begin(); it != wordcounts.end();
                ++it)
        {
            std::cout << "Who(key = first): " << it->first;
            std::cout << " Score(value = second): " << it->second << '\n';
        }
    }
}

关于这个麻烦我不知道,因为我是初学者使用地图结构。

我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

我认为可能有帮助的是创建第二个地图,通过此索引索引具有相同wordcount-index的string列表,如下所示(类似于histogram):

std::map<int, std::list<std::string> > inverted;

所以当你完成创建wordcounts - map时,你必须像这样手动将每个string插入到倒排索引中(小心,这段代码未经测试!):

// wordcounts to inverted index
for (std::map<std::string, int>::iterator it = wordcounts.begin();
        it != wordcounts.end(); ++it)
{
    int wordcountOfString = it->second;
    std::string currentString = it->first;

    std::map<int, std::list<std::string> >::iterator invertedIt =
            inverted.find(wordcountOfString);
    if (invertedIt == inverted.end())
    {
        // insert new list
        std::list<std::string> newList;
        newList.push_back(currentString);
        inverted.insert(
                std::make_pair<int, std::list<std::string>>(
                        wordcountOfString, newList));
    }
    else
    {
        // update existing list
        std::list<std::string>& existingList = invertedIt->second;
        existingList.push_back(currentString);
    }

}