在一组中循环
Iterating through a set
我有一组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中,为了兼容性,可以编写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)
...
这段代码不是最佳的,因为它可以进行不必要的迭代器比较,但它很有效,而且很简单:
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),在循环中执行的所有操作都是自然的(当然,循环本身除外)这更易于阅读和编写,并且应该更快地运行批量。
相关文章:
- 在 c++ 中拥有一组结构的正确方法是什么?
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 一组值的零开销下标运算符
- 使用一组结构,避免在一组结构中出现重复的结构
- CMake:我们可以为一组不形成可执行文件或库的特定文件指定包含目录吗?
- 合并一组模板专用化
- 如何更好地检查两个 char 变量是否在一组值中?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 在C++中,建议通过数组循环的方式是什么?
- 给定一个枢轴点,按照它们与枢轴点构成的角度递增顺序对一组点进行排序
- 如何制作不允许重复值的 C++ int 数组循环?
- c++在循环中定义一组概率分布
- 如何在循环移动后从给定的字符串中找到一组不同的字符串
- 查找一组循环数据的中位数
- C++:为什么创建的向量没有传递到下一组 for 循环
- 在一组中循环
- 如何循环访问一组集合C++
- 如何从while循环生成的一组输出中找到最大值
- 循环问题:从它自己的成员函数中访问一组对象