gpt4 book ai didi

c++ - 遍历集合

转载 作者:太空宇宙 更新时间:2023-11-04 16:25:29 25 4
gpt4 key购买 nike

我有一组整数设置了一些东西;长度为 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]
}

首先我尝试用一​​个迭代器实现它,但后来我意识到不可能从另一个迭代器的位置 +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)
...

关于c++ - 遍历集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12354205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com