简体   繁体   English

为什么 std::set_difference 不删除重复项?

[英]Why does std::set_difference not remove duplicates?

cppreference states that std::set_difference : cppreference指出std::set_difference

Copies the elements from the sorted range [first1, last1) which are not found in the sorted range [first2, last2) to the range beginning at d_first.将排序范围 [first1, last1) 中未在排序范围 [first2, last2) 中找到的元素复制到从 d_first 开始的范围。

With that said, I would expect the following MWE to output 2 4 , because only 2 and 4 are not in the second set.话虽如此,我希望以下 MWE 到 output 2 4 ,因为只有 2 和 4 不在第二组中。

#include <algorithm>
#include <set>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> A{1, 1, 2, 2, 2, 3, 3, 4};
    std::set<int> B{1, 3};
    std::set<int> difference;
    std::set_difference(
        A.cbegin(), 
        A.cend(), 
        B.cbegin(),
        B.cend(), 
        std::inserter(difference, difference.end())
    );

    std::for_each(difference.cbegin(), difference.cend(), [](int n) {
        std::cout << n << " ";
    });
    std::cout << std::endl;
}

However, it appears that this outputs 1 2 3 4 , and I'm not fully sure why.但是,这似乎输出1 2 3 4 ,我不完全确定为什么。 It does what I expect if I change A to only contain 1 2 3 4 Can someone help me understand this?如果我将A更改为仅包含1 2 3 4 ,它会达到我的预期效果 有人可以帮助我理解这一点吗?

I'm not really sure there's a good reason it has to be defined to work that way, but it definitely is how it's defined.我不确定是否有充分的理由必须将其定义为以这种方式工作,但这绝对是它的定义方式。 The standard specifically requires this behavior.该标准特别要求这种行为。 Here's the wording as of N4835 (§[set.difference]/6):这是 N4835 的措辞(§[set.difference]/6):

Remarks: If [first1, last1) contains m elements that are equivalent to each other and [first2, last2) contains n elements that are equivalent to them, the last max(m − n, 0) elements from [first1, last1) is copied to the output range, in order.备注:如果 [first1, last1) 包含 m 个相互等价的元素,而 [first2, last2) 包含 n 个等价的元素,则 [first1, last1) 的最后 max(m − n, 0) 个元素为按顺序复制到 output 范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM