在嵌套多图中搜索C ++中的值?

时间:2018-11-01 23:25:16

标签: c++ nested multimap

我正在尝试搜索一个嵌套的MultiMap,其中外部Multimap具有一个字符串键值,每个键的值是另一个multimap,其中包含字符串作为键值对,如下所示:

 multimap<string,map<string, string>> myMultMap;
myMultMap.insert(make_pair("distinct", makeMap("noun", "This is the first definition")));
myMultMap.insert(make_pair("distinct", makeMap("verb", "This is the second definition")));
myMultMap.insert(make_pair("distinct", makeMap("adjective", "This is the third definition")));
myMultMap.insert(make_pair("book", makeMap("noun", "This is the book noun definition")));
myMultMap.insert(make_pair("book", makeMap("verb", "This is the book verb definition")));
myMultMap.insert(make_pair("other", makeMap("noun", "This is the other noun definition")));
myMultMap.insert(make_pair("dumb", makeMap("noun", "This is the dumb noun definition")));

我正在尝试使其成为一种交互式,可搜索的地图/词典,以便如果我输入“ book”,它将输出关键字“ book”以及动词定义和名词定义:

输出:

书[名词]:这是书中的名词定义

book [verb]:这是书籍动词定义

到目前为止,我已经尝试在multimap类中使用迭代器和.equals_range()方法,并且如果我将“ 名词”用作第二个搜索参数,但如果我搜索动词没有任何显示。

pair <multimap<string, string>::iterator, multimap<string, string>::iterator> ret;

auto iter = myMultMap.find(str)->second;
ret = iter.equal_range("noun");


for (multimap<string,string>::iterator it=ret.first; it!=ret.second; ++it) {
    std::cout << str << " =>";
    std::cout << ' ' << it->second;
}
std::cout << '\n';

任何帮助将不胜感激。

编辑

我忘了补充说,外部多重地图的每个语音键部分也有多个定义。 myMultMap.insert(make_pair("book", makeMap("noun", "This is the 1 definition"))); myMultMap.insert(make_pair("book", makeMap("verb", "This is the book verb def1"))); myMultMap.insert(make_pair("book", makeMap("verb", "This is the book verb def 2"))); myMultMap.insert(make_pair("book", makeMap("verb", "This is the book def 1"))); myMultMap.insert(make_pair("book", makeMap("noun", "This is the book noun def 2")));

1 个答案:

答案 0 :(得分:1)

使用这些复杂的数据结构,您只需要仔细考虑每个元素返回哪种类型以及如何进一步引用该类型的方式。首先是精神上的挑战,但实践起来会更容易。

我认为也许是这样的事情

void output(std::multimap<std::string, std::map<std::string, std::string>> mm, 
    std::string const& item)
{
    auto range = mm.equal_range(item);

    for(auto item_iter = range.first; item_iter != range.second; ++item_iter)
        for(auto const& entry: item_iter->second)
            std::cout << item_iter->first << " [" << entry.first << "]: " << entry.second << '\n';
}

外层是std::multimap,它可以具有重复的键,因此equal_range是搜索给定键的常用方法。

这会为您提供迭代器的列表,因此您可以遍历这些迭代器。每个人都取消引用std::pair<std::string, std::map<std::string, std::string>

然后可以使用基于范围的for循环对std::map进行迭代,如图所示。