如何检查一个向量是否是另一个向量的子集?

发布于 2024-09-30 10:26:47 字数 105 浏览 0 评论 0原文

目前,我认为最好的选择是使用 std::set_intersection,然后检查较小输入的大小是否与 set_intersection 填充的元素数量相同。

有更好的解决方案吗?

Currently, I think my best option is to use std::set_intersection, and then check if the size of the smaller input is the same as the number of elements filled by set_intersection.

Is there a better solution?

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

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

发布评论

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

评论(2

厌倦 2024-10-07 10:26:47

试试这个:

if (std::includes(set_one.begin(), set_one.end(),
                  set_two.begin(), set_two.end()))
{
// ...
}

关于includes()

includes() 算法比较两个
排序序列并返回 true if
[start2,
finish2) 包含在范围内
[开始1,结束1)。它返回错误
否则。 include() 假设
序列使用排序
运算符<(),或使用谓词
比较。

跑进

最多 ((完成1 - 开始1) + (完成2
- start2)) * 执行 2 - 1 次比较。

再加上 O(nlog(n)) 用于对向量进行排序。你不会比这更快地得到它。

Try this:

if (std::includes(set_one.begin(), set_one.end(),
                  set_two.begin(), set_two.end()))
{
// ...
}

About includes().

The includes() algorithm compares two
sorted sequences and returns true if
every element in the range [start2,
finish2) is contained in the range
[start1, finish1). It returns false
otherwise. includes() assumes that the
sequences are sorted using
operator<(), or using the predicate
comp.

runs in

At most ((finish1 - start1) + (finish2
- start2)) * 2 - 1 comparisons are performed.

Plus O(nlog(n)) for sorting vectors. You won't get it any faster than that.

ζ澈沫 2024-10-07 10:26:47

如果您使用的是 c++-20 或更高版本,则可以使用 std ::ranges::includes 执行相同的操作。

assert(ranges::includes(vector<int>{2, 4, 6, 8, 10}, vector<int>{4}));
assert(ranges::includes(vector<int>{2, 4, 6, 8, 10}, vector<int>{4, 6}));

If you are using c++-20 or higher, you can use the std::ranges::includes to do the same.

assert(ranges::includes(vector<int>{2, 4, 6, 8, 10}, vector<int>{4}));
assert(ranges::includes(vector<int>{2, 4, 6, 8, 10}, vector<int>{4, 6}));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文