C++ Set Operations on Sorted Ranges: set_union, intersection & difference

C++ Set Operations on Sorted Ranges: set_union, intersection & difference

이 글의 핵심

Sorted-range set algorithms in C++: math meaning, includes, and practical patterns.

What are set algorithms?

They implement set operations on sorted ranges (not only std::set): union, intersection, difference, symmetric difference, and subset test includes.

Operations

AlgorithmNotationMeaning
set_unionAll keys in order
set_intersectionIn both
set_differenceA − BIn A not in B
set_symmetric_differenceIn exactly one
includesSubsequence / subset test
flowchart TD
    A["A = 1, 2, 3, 4"]
    B["B = 3, 4, 5, 6"]
    
    A --> U["Union\n1, 2, 3, 4, 5, 6"]
    B --> U
    
    A --> I["Intersection\n3, 4"]
    B --> I
    
    A --> D["Difference A-B\n1, 2"]
    B --> D
    
    A --> S["Symmetric diff.\n1, 2, 5, 6"]
    B --> S

Requirements

Sort both ranges with the same comparator before calling. Output typically via std::back_inserter.


includes

Tests whether the second sorted range appears as a subsequence of the first (subset / “all of B in A” for unique sorted keys).


Production patterns

Permissions (sorted includes), tag intersection, change detection with two set_difference calls — same structure as Korean article.


FAQ

Covers definition, sorting requirement, duplicates, O(n+m) merge phase, includes, std::set container vs algorithms, back_inserter, and Effective STL / cppreference.


  • C++ Algorithm Sort
  • C++ Algorithm Partition
  • C++ Algorithm MinMax

Keywords

set_union, set_intersection, set_difference, set_symmetric_difference, includes, sorted range, STL