在一组中循环

Iterating through a set

本文关键字:一组 循环      更新时间:2023-10-16

我有一组int集;长度为52。我使用循环来迭代如下所示的集合:

for(iterator A from 1st to 48th element)
 for(iterator B from A+1 to 49th element)
  for(iterator C from B+1 to 50th element)
   for(iterator D from C+1 to 51th element)
    for(iterator E from D+1 to 52th element)
    {
       //save the values from the actual positions in set in array[5]
    }

首先我尝试使用迭代器,但后来我意识到从position of another iterator +1启动迭代器是不可能的。然后我尝试使用指针并跳过值,但我只正确地分配了第一个值,然后我不能跳到第二个值等。

我的代码是:

set<int> tableAll;
for(int i=4; i!=52; ++i) 
  tableAll.insert(i);
const int * flop1 = & * tableAll.begin();
cout << * flop1 << endl;
flop1++;
cout << * flop1 << endl;

当我cout指针flop1的值时,我得到4,这没关系,但当我在屏幕上增加它并再次cout时,我获得0,然后,49,然后0,然后1,然后0而不是5、6、7、8和9。

那么,如何正确地遍历我的集合呢?我认为使用指针将比某些迭代器解决方案更快。

您绝对可以从另一个迭代器的偏移量进行迭代:

for (auto a(std::begin(mySet)), a_end(std::prev(std::end(mySet), 4));
        a != a_end; ++a)
    for (auto b(std::next(a)), b_end(std::next(a_end); b != b_end; ++b)
        ...

在C++03中,为了兼容性,可以编写nextbegin

template<typename Iterator> Iterator next(Iterator it, int n = 1) {
    std::advance(it, n);
    return it;
}
template<typename Iterator> Iterator prev(Iterator it, int n = 1) {
    std::advance(it, -n);
    return it;
}
for (std::set<int>::const_iterator a(mySet.begin()),
        a_end(std::prev(mySet.end(), 4)); a != a_end; ++a)
    for (std::set<int>::const_iterator b(std::next(a)),
            b_end(std::next(a_end)); b != b_end; ++b)
        ...

这段代码不是最佳的,因为它可以进行不必要的迭代器比较,但它很有效,而且很简单:

set<int> tableAll;
for(int i=0; i!=52; ++i)
  tableAll.insert(i);
for( set<int>::iterator iA=tableAll.begin(); iA != tableAll.end(); ++iA  )
    for( set<int>::iterator iB=iA; ++iB != tableAll.end();  )
        for( set<int>::iterator iC=iB; ++iC != tableAll.end();  )
            for( set<int>::iterator iD=iC; ++iD != tableAll.end();  )
                for( set<int>::iterator iE=iD; ++iE != tableAll.end();  ) 
{
   cout<<*iA<<' '<<*iB<<' '<<*iC<<' '<<*iD<<' '<<*iE<<endl;
}

我建议将set复制到临时std::vector。对于向量和O(1),在循环中执行的所有操作都是自然的(当然,循环本身除外)这更易于阅读和编写,并且应该更快地运行批量