std::set_symmetric_difference
| 在标头 <algorithm> 定义
|
||
| (1) | (C++20 起为 constexpr) |
|
| |
(2) | (C++17 起) |
| (3) | (C++20 起为 constexpr) |
|
| |
(4) | (C++17 起) |
计算两个有序范围的对称差:将处于任一范围中,但未在两个范围中均被找到的元素,复制到始于 d_first 的范围。输出范围也保持有序。
如果 [first1, last1) 中有 m 个互相等价的元素,并且 [first2, last2) 中有 n 个与它们等价的元素,那么将保持顺序地复制前 std::abs(m - n) 个元素到输出范围:
- 如果
m > n,那么从[first1,last1)复制这些元素中的最后m - n个。 - 如果
n > m,那么从[first2,last2)复制这些元素中的最后n - m个。
[first1, last1) 或 [first2, last2) 没有按 comp 排序,那么行为未定义。policy 执行。|
|
(C++20 前) |
|
|
(C++20 起) |
如果输出范围与 [first1, last1) 或 [first2, last2) 重叠,那么行为未定义。
参数
| first1, last1 | - | 第一个有序元素范围的迭代器对 |
| first2, last2 | - | 第二个有序元素范围的迭代器对 |
| d_first | - | 输出范围的起始 |
| policy | - | 所用的执行策略 |
| comp | - | 比较函数对象(即满足比较 (Compare) 概念的对象),在第一参数小于(即先 序于)第二参数时返回 true。比较函数的签名应等价于如下:
虽然签名不必有 |
| 类型要求 | ||
-InputIt1, InputIt2 必须满足老式输入迭代器 (LegacyInputIterator) 。
| ||
-OutputIt 必须满足老式输出迭代器 (LegacyOutputIterator) 。
| ||
-ForwardIt1, ForwardIt2, ForwardIt3 必须满足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-Compare 必须满足比较 (Compare) 。
| ||
返回值
所构造范围的尾后迭代器。
复杂度
给定 N1 为 std::distance(first1, last1),N2 为 std::distance(first2, last2):
operator<(C++20 前)std::less{}(C++20 起) 进行比较。comp。异常
拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy,行为由实现定义。 - 如果算法无法分配内存,那么抛出 std::bad_alloc。
可能的实现
| set_symmetric_difference (1) |
|---|
template<class InputIt1, class InputIt2, class OutputIt>
OutputIt set_symmetric_difference(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2, OutputIt d_first)
{
while (first1 != last1)
{
if (first2 == last2)
return std::copy(first1, last1, d_first);
if (*first1 < *first2)
*d_first++ = *first1++;
else
{
if (*first2 < *first1)
*d_first++ = *first2;
else
++first1;
++first2;
}
}
return std::copy(first2, last2, d_first);
}
|
| set_symmetric_difference (3) |
template<class InputIt1, class InputIt2, class OutputIt, class Compare>
OutputIt set_symmetric_difference(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first, Compare comp)
{
while (first1 != last1)
{
if (first2 == last2)
return std::copy(first1, last1, d_first);
if (comp(*first1, *first2))
*d_first++ = *first1++;
else
{
if (comp(*first2, *first1))
*d_first++ = *first2;
else
++first1;
++first2;
}
}
return std::copy(first2, last2, d_first);
}
|
示例
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v1{1, 2, 3, 4, 5, 6, 7, 8};
std::vector<int> v2{5, 7, 9, 10};
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<int> v_symDifference;
std::set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(),
std::back_inserter(v_symDifference));
for (int n : v_symDifference)
std::cout << n << ' ';
std::cout << '\n';
}
输出:
1 2 3 4 6 8 9 10
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 291 | C++98 | 未指定如何处理输入范围中等价的值 | 已指定处理方法 |
