C++ std::set_difference详解

  算法set_difference可以用来求两个集合的差集,本文给出一个默认类型的示例和一个自定义类型的示例

#include 
#include 
#include 
#include 
#include 
 
auto print = [](const auto& v, std::string_view end = "") {
    std::cout << "{ ";
    for (auto i : v) std::cout << i << ' ';
    std::cout << "} " << end;
};
 
struct Order // a struct with some interesting data
{
    int order_id;
 
    friend std::ostream& operator<<(std::ostream& os, const Order& ord) {
        return os << ord.order_id << ',';
    }
};
 
int main() {
    const std::vector v1 {1, 2, 5, 5, 5, 9};
    const std::vector v2 {2, 5, 7};
    std::vector diff;
 
    std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(),
                        std::inserter(diff, diff.begin()));
    print(v1, "∖ ");
    print(v2, "= ");
    print(diff, "\n");
 
    // we want to know which orders "cut" between old and new states:
    std::vector old_orders { {1}, {2}, {5}, {9} };
    std::vector new_orders { {2}, {5}, {7} };
    std::vector cut_orders;
 
    std::set_difference(old_orders.begin(), old_orders.end(),
                        new_orders.begin(), new_orders.end(),
                        std::back_inserter(cut_orders),
                        [](auto& a, auto& b) { return a.order_id < b.order_id; });
 
    std::cout << "old orders = "; print(old_orders, "\n");
    std::cout << "new orders = "; print(new_orders, "\n");
    std::cout << "cut orders = "; print(cut_orders, "\n");
}

输出:

{ 1 2 5 5 5 9 } ∖ { 2 5 7 } = { 1 5 5 9 } 
old orders = { 1, 2, 5, 9, } 
new orders = { 2, 5, 7, } 
cut orders = { 1, 9, }

你可能感兴趣的:(C++,数据结构,c++,stl)