如何在 for 循环中同时使用双端队列的两个连续元素?
How do I use two consecutive elements of a deque at once in a for loop?
我必须处理双端队列中的元素(从第一个到最后一个),但在每次迭代中我都需要使用一个元素和下一个元素。所以我正在尝试编写一个以 mydeque.begin() 开始并在 mydeque[mydeque.size()-1] 处结束的 for 循环。还;我想知道我的迭代器 deque::iterator 是否有 next 方法 (it->next()),以进行像 *it - *it->next() 这样的操作。非常感谢。
编辑:我最初的解决方案确实有点容易出错且不精确。
这可以使用迭代器轻松完成,请看这个小例子:
#include <deque>
#include <iostream>
int main() {
std::deque<int> test = {1,2,3,4,5,6,7};
for(auto i = test.begin(); i != test.end(); ++i) {
auto next = std::next(i);
if(next != test.end()) {
std::cout << *i << " " << *next << std::endl;
}
}
}
您可以简单地将迭代器递增 2 并使用 std::next 来选择以下项目(因为 std::next 的偏移量默认为 1)。
方法如下:
#include <deque>
#include <iostream>
int main() {
std::deque<int> test = {1,2,3,4,5,6,7,8};
for(auto i = test.begin(); i != test.end(); i++) {
auto next = std::next(i);
std::cout << *i << *next << std::endl;
if(next==test.end())
{
//Do something. This is the last element.
break;
}
}
}
编辑: 注意只有一个元素的双端队列。通过执行 if(test.begin()==test.end())
.
等检查来执行此操作
我必须处理双端队列中的元素(从第一个到最后一个),但在每次迭代中我都需要使用一个元素和下一个元素。所以我正在尝试编写一个以 mydeque.begin() 开始并在 mydeque[mydeque.size()-1] 处结束的 for 循环。还;我想知道我的迭代器 deque::iterator 是否有 next 方法 (it->next()),以进行像 *it - *it->next() 这样的操作。非常感谢。
编辑:我最初的解决方案确实有点容易出错且不精确。
这可以使用迭代器轻松完成,请看这个小例子:
#include <deque>
#include <iostream>
int main() {
std::deque<int> test = {1,2,3,4,5,6,7};
for(auto i = test.begin(); i != test.end(); ++i) {
auto next = std::next(i);
if(next != test.end()) {
std::cout << *i << " " << *next << std::endl;
}
}
}
您可以简单地将迭代器递增 2 并使用 std::next 来选择以下项目(因为 std::next 的偏移量默认为 1)。
方法如下:
#include <deque>
#include <iostream>
int main() {
std::deque<int> test = {1,2,3,4,5,6,7,8};
for(auto i = test.begin(); i != test.end(); i++) {
auto next = std::next(i);
std::cout << *i << *next << std::endl;
if(next==test.end())
{
//Do something. This is the last element.
break;
}
}
}
编辑: 注意只有一个元素的双端队列。通过执行 if(test.begin()==test.end())
.