gpt4 book ai didi

c++ - 就地 C++ 设置交集

转载 作者:IT老高 更新时间:2023-10-28 21:57:41 28 4
gpt4 key购买 nike

在 C++ 中相交两个集合的标准方法是执行以下操作:

std::set<int> set_1;  // With some elements
std::set<int> set_2; // With some other elements
std::set<int> the_intersection; // Destination of intersect
std::set_intersection(set_1.begin(), set_1.end(), set_2.begin(), set_2.end(), std::inserter(the_intersection, the_intersection.end()));

我将如何进行就地设置的交叉点?也就是说,我希望 set_1 有调用 set_intersection 的结果。显然,我可以只做一个 set_1.swap(the_intersection),但这比就地相交效率低很多。

最佳答案

我想我明白了:

std::set<int>::iterator it1 = set_1.begin();
std::set<int>::iterator it2 = set_2.begin();
while ( (it1 != set_1.end()) && (it2 != set_2.end()) ) {
if (*it1 < *it2) {
set_1.erase(it1++);
} else if (*it2 < *it1) {
++it2;
} else { // *it1 == *it2
++it1;
++it2;
}
}
// Anything left in set_1 from here on did not appear in set_2,
// so we remove it.
set_1.erase(it1, set_1.end());

有人发现任何问题吗?两组的大小似乎是 O(n)。根据cplusplus.com , std::set erase(position) 是摊销常数,而 erase(first,last) 是 O(log n)。

关于c++ - 就地 C++ 设置交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1773526/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com