迭代一组

时间:2012-09-10 14:51:35

标签: c++ pointers iterator set

我有一套整齐的东西;长度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。

那么如何正确迭代我的设置呢?我假设使用指针比一些迭代器解决方案更快。

3 个答案:

答案 0 :(得分:4)

你绝对可以从另一个迭代器的偏移量中迭代:

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)
        ...

答案 1 :(得分:1)

这段代码不是最优的,因为它不需要迭代器比较,但是有效并且很简单:

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;
}

答案 2 :(得分:0)

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

相关问题