[英]std::unordered_set::find - construct an instance only for find()
A lot of times I see my key
is actually inside my value
. 很多时候,我看到我的
key
实际上是我的value
。
For example: 例如:
struct Elem {
int key;
// ... Other variables ...
}
That makes me want to use std::unordered_set instead of std::unordered_map
, because I already have the key
stored inside my value
- no need to waste more place for std::unordered_map
's .first
( key
). 这使我想使用std :: unordered_set而不是
std::unordered_map
,因为我已经将key
存储在value
-无需为std::unordered_map
的.first
( key
)浪费更多的空间。
Then I start implementing with std::unordered_set
and get to the place I need to perform a find()
over my std::unordered_set
. 然后,我开始使用
std::unordered_set
实现,并到达需要在std::unordered_set
上执行find()
的地方。
Then I realize I need to create an empty-shell Elem
so I would be able to find()
, beacuse std::unordered_set::find
gets a Key
for input 然后我意识到我需要创建一个空壳的
Elem
这样我就能find()
,因为std::unordered_set::find
会得到一个输入Key
template < class Key, // unordered_set::key_type/value_type
class Hash = hash<Key>, // unordered_set::hasher
class Pred = equal_to<Key>, // unordered_set::key_equal
class Alloc = allocator<Key> // unordered_set::allocator_type
> class unordered_set;
Sometimes building an empty-shell Elem
is hard / wasteful / maybe even not possible? 有时候建立一个空壳的
Elem
很难/浪费/甚至不可能?
For example, when my key/value is 例如,当我的键/值是
c'tor
(not constructing the instance only with the key
) c'tor
的类(不仅使用key
构造实例) Q. Am I missing something? 问:我想念什么吗?
Q. Is there a way to do find()
that isn't wasteful? 问:有没有办法做
find()
呢? I mean that doesn't make me create an instance I didn't want to 我的意思是这并不能使我创建一个我不想创建的实例
When choosing a data structure to hold your data you need to consider your use case. 选择数据结构来保存数据时,您需要考虑用例。
If you want to look up data from a key you should use a map
. 如果要从键查找数据,则应使用
map
。 If you just want to store unique values in a collection and you don't need to look them up use set
. 如果您只想在集合中存储唯一值,而无需使用use
set
查找它们。
I don't see why its so much trouble to insert a element as map.emplace_back(elem.key, elem)
vs set.emplace_back(elem)
if it means that down the road you can just query the elem as map.at(key)
or map[key]
vs having create an empty elem
. 我不明白为什么插入一个元素作为
map.emplace_back(elem.key, elem)
vs set.emplace_back(elem)
这么麻烦,如果这意味着在路上您可以将elem作为map.at(key)
或map[key]
与创建一个空的elem
。
Besides, std::set
does the whole key thingamajig (roughly) underwater anyway. 此外,
std::set
会(大致)在水下进行整个关键的东西。 (source: What is the difference between set vs map in C++? ) (来源: C ++中的set vs map有什么区别? )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.