访问矢量中的地图:map<string,vector<map<string,矢量<int>> > >

Get access to map in a vector: map<string, vector<map<string, vector<int> > > >

本文关键字:gt lt string map vector 矢量 int 地图 访问      更新时间:2023-10-16

我有以下自己创建的数据类型:

typedef map<string, vector<map<string, vector<int> > > > Entry;

表示以下数据结构:

Filename | vector<map<Word, vector<LineNumber> > > 

表示每个FileName包含许多单词,每个单词包含linNumbers。它代表了多个文件中单词的索引。

为此假设我编写了一个函子,它应该将fileName, word和lnr添加到我的数据结构中:

FileWordLineAdder(string fileName, Entry wordLnr, int lnr) : fileName(fileName), entries(wordLnr), lnr(lnr) {
}
void operator()(string word) {
    word = normalize(word);
    if (word.size() == 0)
        return;
    vector<map<string, vector<int> > >& wordLnr = entries[fileName];
/* PROBLEM START */
    //vector<int>& lnrs = wordLnr[word];
    //lnrs.push_back(lnr);
/* PROBLEM END*/
} // operator()

现在我能够将fileName插入到我的数据结构中(参见上面的问题部分),但我无法访问向量中的映射。

有谁能帮帮我吗

我认为你的数据结构设计过度了。对于"file -> word -> linenumbers"的索引,只需:

Filename | map<Word, vector<LineNumber> >

map<string/*filename*/, map<string/*word*/, vector<unsigned long/*lineNumber*/ > > >

可能就足够了。请注意,这个数据结构已经是整个索引。它不是"一个条目",所以你的typedef可能命名错误。

(请注意,我删除了一个级别的"矢量"是在地图上-我认为这是你的问题的实际来源。对于vector<map<...>>,您将有许多用于文件名的单词映射,并且您可能不知道该选择哪一个映射。

我的方案如下:

typedef map<string/*word*/, vector<unsigned long> /*lineNumber*/> IndexInnerMap;
typedef map<string/*filename*/, IndexInnerMap> Index;
    // Get innerMap of specific fileName
    IndexInnerMap& wordLnr = index[fileName];
    // Get vector<lineNumber> of specific word
    vector<unsigned long>& lnrs = wordLnr[word];
    // Add line number to vector
    if (lnrs.empty() || lnrs.back() != lnr) {
        lnrs.push_back(lnr);
    } // if

谢谢你的帮助;)