stl::set 的随机访问和更新
我使用 stl::set 来保持插入元素时的排序。我的问题是关于随机访问。如果我有一个复杂的类(例如,难以初始化),我发现它很容易插入,因为我在类中定义了 less 运算符。但如果关键是类本身,我需要如何访问该类?用find()?我需要初始化一个复杂的类才能找到我的类?
所以我的问题是:当元素是难以初始化的复杂类时,如何随机访问集合元素?
谢谢
I'm using a stl::set to keep elements sorted as they are inserted. My question is about the random access. If I have a complex class(difficult to init, for example), I found that is easy to insert, because I define the less operator into class. But if the key is the class itself, how do I need to access to the class? With a find()? I need to init a complex class only to find my class?
So my question is: how to random access to a set elements when elements are complex classes difficult to initialize?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以:
1) 为您的类创建一个特殊的“lightweigt”初始值设定项,以创建对象的“lightweight”版本,并仅使用此类“轻量级”对象作为访问映射的键
2) 使用映射而不是集合。
我更喜欢第二种解决方案。
you can:
1) create a special "lightweigt" initializer for your class to create "ligtweight" version of your object and use such "lightweight" objects only as keys to access the map
2) use a map instead of a set.
I'd prefer the second solution.
我认为这是不可能的:正如您已经注意到的, std::set<>::find 成员函数需要一个 const key_type & (其中,
std::set
与value_type
相同)。如果您反对构建成本高昂,那么您可能最好使用 std::map (这也是一个排序容器),其值可能是您类型上的(智能)指针。
I don't think it is possible : as you already noticed, the
std::set<>::find
member function expects aconst key_type &
(which, in astd::set
is identical tovalue_type
).If you object is expensive to construct, chances are that you should better use a
std::map
(which also is a sorted container), possibly with values being (smart) pointers on your type.Set 不支持随机访问迭代器。如果您想要其他方式来比较对象(不会使用运算符 <),您必须执行以下操作
1)第一种方式
2)或者您可以使用函数类而不是像这样的函数
另外我认为您必须查看功能标头。在那里您可以找到一些可以在功能中使用的函数类。
Set doesn't support random access iterator. If you want other way to compare objects(won't use operator <) you must do following
1)first way
2)Or you can use function-class instead of function like this
Also I think you must look at functional header. There you can find some function-classes which you can use in the feauture. http://www.cplusplus.com/reference/std/functional/
必须用一套吗?
您可能最好使用映射并为复杂类生成键(可能是数字索引或字符串),然后使用复杂类的对象作为值。
只需确保您的密钥遵循与值相同的排序规则即可。 std::map 是作为树实现的,因此它也会根据键对项目进行排序。
Do you have to use a set?
You might be better off using a map and generating a key (maybe a numerical index or a string) for your complex class, and then using the objects of the complex class as a value.
Just make sure your key follows the same ordering rules as the value. std::map is implemented as a tree, so it will also keep the items sorted according to the keys.
您只需要定义一个 less 结构体,如下所示:
You only need to define a less struct like this: