0

假设我在地图中有多个具有相同值的键。那么在这种情况下,我如何检索与查询匹配的所有键。

或者,是否有可能告诉查找操作搜索特定值。
我正在使用std::mapC++。

4

5 回答 5

2

像这样的东西对你有用吗:

void FindKeysWithValue(Value aValue, list<Key>& aList)
{
    aList.clear();

    for_each(iMap.begin(), iMap.end(), [&] (const pair<Key, Value>& aPair)
    {
        if (aPair.second == aValue)
        {
            aList.push_back(aPair.first);
        }
    });
}
于 2012-11-02T20:56:29.000 回答
1

唯一的方法是遍历地图。

此链接可能有用:反向地图查找

于 2012-11-02T20:56:42.243 回答
1

关联容器可能对您没有太大帮助,因为std::map<K, V>键恰好是唯一的,并且您选择的查询与您使用的排序关系匹配的机会可能不会太高。如果顺序匹配,您可以使用std::map<K, V>成员lower_bound()upper_bound()。因为std::multimap<K, V>你也可以使用equal_range().

一般来说,即,如果您的查询与订单无关,您可以使用它std::copy_if()来获取与谓词匹配的对象序列:

Other other;
// ...
std::vector<Other::value_type> matches;
std::copy_if(other.begin(), other.end(), 
             std::back_inserter(matches), predicate);

当复制元素太昂贵时,您可能应该考虑使用std:find_if()

for (auto it(other.begin());
    other.end() != (it = std::find_if(it, other.end(), predicate));
    ++it) {
   // do something with it
}
于 2012-11-02T20:57:39.237 回答
1

如果您想要快速访问并且您不介意使用更多空间,那么您可以维护另一个映射,该映射被存储为值,键。在您的情况下,您需要处理重复的值(您将作为键存储)。

不是一个好主意,但绝对是一个选择。

于 2012-11-02T21:01:04.387 回答
0

Amap用于有效查找键。基于值的查找效率不高,您基本上必须遍历地图,自己提取匹配项:

for(map<A,B>::iterator i = m.begin(); i != m.end(); i++)
    if(i->second == foo)
        you_found_a_match();

如果你打算经常这样做,你可以用另一种方式建立一个多图映射,这样你就可以有效地执行基于值的查找:

multimap<B,A> reverse;
for(map<A,B>::iterator i = m.begin(); i != m.end(); i++)
    reverse.insert(pair<B,A>(i->second,i->first));

您现在可以轻松找到具有给定值的键:

matches = reverse.equal_range(value);
for(multimap<B,A>::iterator i = matches.first; i != matches.second; i++)
    A & key = i->second;

如果这些映射不会持续增长,那么简单地维护一个向量 > 可能会更有效,根据该值为其定义一个比较器,然后使用 equal_range 代替。

于 2012-11-02T21:02:51.207 回答