0

I have two sets:

std::set<int> one;
std::set<int> two;

Each set contains indices of some objects - I need to deactivate the indices only in one, and activate the indices only in two. The indices that are in both will remain as is.

If these were sorted vectors, I would do something like:

int c1 = 0; int c2 = 0;
while(true){
    if(one[c1] < two[c2]){
       one[c1].deactivate();
       c1++;
    }else if(one[c1]==two[c2]){
       c1++; c2++;
    }else{
       two[c2].activate();
       c2++;
    }
    if(c1 == one.size() || c2 == two.size()){
        break;
    }
}

while(c1<one.size()){
   one[c1].deactivate();
   c1++;
}
while(c2<two.size()){
   two[c2].activate();
   c2++;
}

Example:

  • one = {1,3,5,6,7,8,10}

  • two = {2,4,6,8,10,12}

  • Before running the algorithm:

  • Active: 1,3,5,6,7,8,20

  • After running the algorithm:

  • Active: 2,4,6,8,10,12

But as these are sets, I'm not sure how to iterate over them this way. How do I accomplish the same thing ?

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190
  • There's not "good" way to do it in c++11. In c++23 exist [`std::ranges::views::zip_view`](https://en.cppreference.com/w/cpp/ranges/zip_view). – Sugar Jan 12 '23 at 09:48
  • Forget about `while(true)` when you just want to iterate over a container (put the running condition in it instead) – Fareanor Jan 12 '23 at 09:50
  • 3
    The code you have above will translate pretty directly into code using set iterators (or vector iterators for that matter). – john Jan 12 '23 at 10:06
  • I suppose `two[c2].activate();` is some hypothetical syntax, but it should be `two.activate(c2)` , because `int` has no member functions at all – 463035818_is_not_an_ai Jan 12 '23 at 10:23
  • Is the starting list of active indices actually 1, 3, 5, 6, 7, 8, **10**? – Bob__ Jan 12 '23 at 10:37
  • 1
    This particular problem is probably solved better with set operations [set_difference](https://en.cppreference.com/w/cpp/algorithm/set_difference) and [set_intersection](https://en.cppreference.com/w/cpp/algorithm/set_intersection). – j6t Jan 12 '23 at 11:15

1 Answers1

3

How to iterate over two sets at the same time?

You can use iterators for this:

auto it1 = one.begin();
auto it2 = two.begin();
while (it1 != one.end() && it2 != two.end()) {
    int i1 = *it1;
    int i2 = *it2;
    
    // Do something with indexes

    it1++;
    it2++;
}
marcinj
  • 48,511
  • 9
  • 79
  • 100