我需要一个具有多个值的键。你会推荐什么数据结构? [英] I need to have a key with multiple values. What datastructure would you recommend?

查看:199
本文介绍了我需要一个具有多个值的键。你会推荐什么数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



words [0] =the

words [1] =dog

words [2] =jumped

words [3] =over

words [4] =

words [5] =wall。

words [6] =the

words [7] =cat

words [8] =fall

words [9] =off

words [10] =the br />
words [10] =house。


(愚蠢的例子,但它适用于此)



每个单词都将是一个键,它的下一个字是它的价值。所以over=>。一些键可以有多个值。例如,the=>dog|| 墙|| 猫|| 屋。该值从那个密钥的随机选择。



当程序运行时,随机选择一个单词并作出一个句子。所以它可能是这样的:猫从狗掉下来。



我尝试实现一个地图(映射myMap;),但这只允许每个键一个值我认为)。



希望我解释这个权利。

解决方案

你可以使用来自STL的multimap并使用调用

  pair< iterator,iterator> equal_range(const key_type& k)

获取与您的密钥匹配的一系列迭代器



个人我发现这个稍微笨重,因为必须处理迭代器范围,而不是仅仅得到一个代表该键的所有值的对象。要绕过,您也可以将矢量存储在常规地图中,并将您的字符串添加到向量。


I have an string array filled with words from a sentence.

words[0] = "the"
words[1] = "dog"
words[2] = "jumped"
words[3] = "over"
words[4] = "the"
words[5] = "wall."
words[6] = "the"
words[7] = "cat"
words[8] = "fell"
words[9] = "off"
words[10] = "the"
words[10] = "house."
etc. (Stupid example, but it works for this)

Each word will be a key with it's following word as it's value. so "over" => "the". Some keys can have multiple values. For example, "the" => "dog" || "wall" || "cat" || "house". The value is randomly chosen from those for that key.

When the program runs it picks a word at random and makes a sentence. So it could be something like: "the cat fell off the dog".

I tried implementing a map (map myMap;) but this allows only one value per key (I think).

Hope I explained this right.

解决方案

you can use a multimap from the STL and use the call

pair<iterator, iterator> equal_range(const key_type& k)

to get a range of iterators that match your key

personally i find this slightly clunky due to having to deal with iterator ranges rather than just getting an object back that represents all values for that key. to get around that you could also store a vector in a regular map and add your strings to the vector.

这篇关于我需要一个具有多个值的键。你会推荐什么数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆