我有一组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。
那么如何正确地遍历我的集合呢?我假设使用指针会比一些迭代器解决方案更快。
发布于 2012-09-10 23:02:13
你绝对可以从另一个迭代器的偏移量中进行迭代:
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中,为了兼容,您可以编写next
和begin
:
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)
...
发布于 2012-09-10 23:19:18
这段代码并不是最优的,因为它做了不必要的迭代器比较,但工作起来很简单:
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;
}
发布于 2012-09-11 00:04:23
我建议将set
复制到临时std::vector
。您在循环中执行的所有操作对于向量和O(1) (当然,循环本身除外)来说都是很自然的,这更容易读取和写入,并且应该可以更快地运行lot。
https://stackoverflow.com/questions/12354205
复制相似问题