In-place C++ set intersection

前端 未结 3 1600
南方客
南方客 2020-12-28 17:39

The standard way of intersecting two sets in C++ is to do the following:

std::set set_1;  // With some elements
std::set set_2;  // Wit         


        
3条回答
  •  粉色の甜心
    2020-12-28 18:14

    I think I've got it:

    std::set::iterator it1 = set_1.begin();
    std::set::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());
    

    Anyone see any problems? Seems to be O(n) on the size of the two sets. According to cplusplus.com, std::set erase(position) is amortized constant while erase(first,last) is O(log n).

提交回复
热议问题