我有两组:
std::set<int> one;
std::set<int> two;
每个集合包含一些对象的索引——我只需要取消一个对象的索引,激活两个对象的索引。在两个索引中都存在的索引保持不变。
如果这些是排序的向量,我会这样做:
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++;
}
的例子:
one = {1,3,5,6,7,8,10}
two = {2,4,6,8,10,12}
运行算法前:
活动:1,3,5,6,7,8,20
算法运行后:
活跃:2,4,6,8,10,12
但由于这些是集合,我不确定如何以这种方式迭代它们。我怎样才能完成同样的事情呢?
如何同时遍历两个集合?
可以使用迭代器:
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++;
}