使用自定义迭代器设置与向量

发布于 2024-10-02 06:16:29 字数 241 浏览 0 评论 0原文

我知道这个问题可能很快就会被标记为许多其他更受欢迎的问题的重复,但我仍然会问:

我需要一个提供插入重复检查的容器(例如 std::set,但允许我修改已经存在的元素(例如 std::vector)。搜索元素也应该相对较快(这更喜欢 std::set )。使用向量和自定义重复检查 insert_iterator 会比通过删除和重新插入来修改集合元素更好吗

I understand this question may be quickly flagged as a duplicate of many other more popular questions, but I'll still ask it:

I need a container that provides duplicate checking on insert (like std::set, but allows me to modify elements already present (like std::vector). It should also be relatively fast to search for elements (which would prefer std::set again). Would it be better to use a vector and perhaps a custom duplicate-checking insert_iterator instead of modifying set elements by erasing and reinserting them?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

彩虹直至黑白 2024-10-09 06:16:29

是什么阻止您使用 std::set?如果需要修改某个元素,请将其复制、删除,然后重新插入。

What is to stop you from using a std::set? If you need to modify an element, copy it, erase it, then re-insert.

鼻尖触碰 2024-10-09 06:16:29

您考虑过使用地图吗?

参考

地图可能是解决您问题的好方法。

Have you looked into using a map?

Reference

A map may be a good solution to your problem.

七颜 2024-10-09 06:16:29

如果您的字符串很长并且性能至关重要,那么您可能会被一个自定义容器所困扰,该容器包装了诸如并行 vectorset 之类的东西。为集合提供一个自定义比较器,以便它通过指针取消引用来进行比较。要修改元素,请从集合中删除指针,修改字符串,然后重新插入指针。

当您想要删除容器元素时,这会变得有点混乱,因此您需要使用某种形式的延迟删除。那时,您已经非常接近一个成熟的字符串自由对象池了。

如果您在性能关键型代码中使用字符串向量,请注意向量重新分配,它会手动将每个字符串复制到新的内存块中。您可以通过观察即将到来的重新分配、创建一个新的空字符串向量(预先保留为双倍大小),然后在每个元素上使用 string::swap 将旧数据移动到新的更大向量中来绕过它。

当 c++0x 移动语义广泛可用时,事情会好得多。

If your strings are long and performance is critical then you may be stuck with a custom container that wraps something like a parallel vector<string> and set<string *>. Provide a custom comparator for the set so that it dereferences through the pointer to make the comparisons. To modify an element, remove the pointer from the set, modify the string, then reinsert the pointer.

This get a bit messy when you want to remove container elements, so you would want to use some form of lazy deletion. At that point you are very close to a full-blown free-object pool for your strings.

If you're using a vector of strings in performance-critical code, then watch out for the vector reallocations which would manually copy each string into the new memory chunk. You can bypass that by watching for an upcoming reallocation, creating a new vector of empty strings (pre-reserved to double size), and then using string::swap on each element to move the old data into the new larger vector.

Things will be much nicer when c++0x move semantics are widely available.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文