是否有标准算法来检查容器 A 是否是容器 B 的超集?
我正在寻找一种标准算法,给定两个容器 A 和 B,两者都没有重复项,如果 A 的所有元素与 B 的元素比较为 true,则返回 true。我使用了 std::all_of 使用谓词检查另一个容器中的成员资格,但我想知道是否有更优雅的解决方案。
I was looking for a standard algorithm that, given two containers A and B, both with no duplicates, returns true if all the elements of A compares to true with an element of B. I used std::all_of
with a predicate that checks membership in the other container, but I was wondering if there was a more elegant solution..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你的意思是“比较相等的元素”。一个对象只能是一个容器的元素(至少在所有标准容器的情况下)。
这个问题与标题中的问题不同。
对于第一个,有
std::is_permutation
。然而,对于某些容器类型,有更有效的算法。例如,如果容器已排序(例如std::set
),那么您可以简单地比较是否相等。对于第二个,没有通用算法。如果容器已排序,则可以使用
std::includes
。否则,您可以编写一个先排序,然后使用 std::includes 的算法。如果较大的容器具有快速查找(例如无序集),那么这个解决方案很好。
I suppose that you mean "elements that compare equal". One object can only be an element of one container (at least in case of all standard containers).
This question is different from the one in the title.
For the first, there
std::is_permutation
. However, for some container types, there are more efficient algorithms. For example, if the container is sorted (such asstd::set
), then you can simply compare for equality.For the second, there's no general algorithm. If the containers are sorted, then you can use
std::includes
. Otherwise you can write an algorithm that sorts first, and then usesstd::includes
.If the larger container has fast lookup (such as unordered set), then this solution is good.
std::includes 会在两个容器都已排序的情况下执行此操作。
https://godbolt.org/z/dnoM4xPbY
如果它们没有排序,你可以' t/不想对它们进行排序,那么我相信 all_of 方法尽可能高效。
如果性能至关重要,我认为首先排序会更有效,但您应该检查您的特定情况。
std::includes does this provided both containers are sorted.
https://godbolt.org/z/dnoM4xPbY
If you they are not sorted, and you can't/don't want to sort them, then I believe the all_of approach is about as efficient as possible.
If performance is critical I think sorting first is more efficient but you should check for your particular case.