c++ - 如何遍历双向链表(环)的每个 SECOND 元素?
问题描述
RING——线性数据结构,其中终点指向结构的起点。它也称为循环缓冲区、循环队列或循环缓冲区。
我有一个函数要写。它的目的是从原始 RING 生成另一个 RING 结构,但它的长度已定义,问题是它必须是原始 RING 的每个 SECOND 元素。
例子:
原环= 1,2,3,4,5
函数 newRing 被调用:newRing (originalRing, nRing, len1=5)
nRing=1,3,5,2,4
(解释:'1' 是 RING 的第一个元素。每秒意味着我取 3、5 ......但这是 RING,所以它像 1,2,3,4,5,1,2,3, 4,5,... 函数说 nRing 的长度必须为 5,所以我接下来取每个元素:2,4。最后它给出 1,3,5,2,4)
我正在使用迭代器(我必须,学校项目)。
iterator i1 = nRing.begin(); //--- .begin() points to the 'beginning' of the Ring
if (originalRing.isEmpty()){ //---whether originalRing is empty or not
return false;}
if (originalRing.length()==1){ //--- if originalRing no. of elements is 1, returns that Ring
return originalRing;
}
if (len1<=0) //--- doesnt make sense
{return false;}
if(!i1.isNULL()) //--- checks whether iterator is null
{
for(int i = 0; i < len1; i++)
{
nRing.insertLast(i1.getKey()); //insert the element to the end of the Ring
i1++;
}
}
所以在这里,我要问的是 i1++ --- 它一个一个地迭代元素。
我的问题是如何使用定义为每个第二个元素附加的迭代器来定义一个循环?
解决方案
你可以std::stable_partition
用来做这个。它将划分环形缓冲区中的元素,以便 lambda 返回 true 的元素位于返回 false 的元素之前。您可以创建一个有状态/可变 lambda 来为每次迭代切换真/假。
#include <iostream>
#include <vector> // std::vector
#include <algorithm> // std::stable_partition
int main() {
std::vector<int> RING = {1, 2, 3, 4, 5};
for(const auto& v : RING) std::cout << v << " ";
std::cout << "\n";
for(int i = 0; i < 4; ++i) {
std::stable_partition( RING.begin(), RING.end(),
[toggle = false](const auto&) mutable {
return toggle ^= true; // false becomes true and vice-a-versa
}
);
for(const auto& v : RING) std::cout << v << " ";
std::cout << "\n";
}
}
输出:
1 2 3 4 5
1 3 5 2 4
1 5 4 3 2
1 4 2 5 3
1 2 3 4 5
推荐阅读
- php - 如何使用 Eloquent 从两个不同的表中检索数据
- c# - 使用 Gong 拖放对 ICollectionView 中的 Observable 集合进行排序
- javascript - 格式化服务器端 jQuery 数据表
- xamarin - 添加 AndroidX 迁移包后,Xamarin Forms 应用程序无法部署到 Android,错误 MSB4018 Xamarin.Android.Support.v7.AppCompat.dll
- python - 如何修复,TypeError: 不支持的操作数类型为 %: 'NoneType' 和 'int'
- python - KeyError 值问题
- angular - 有没有办法从两个可能的@Inputs 中设置一个变量?(角2+)
- android - 以编程方式更改线性布局背景颜色的问题
- java - Java - 扫描仪不读取带空格的字符串(已解决)
- angular - 在具有反应式表单的 Angular 7 应用程序中,我如何修改此方法以使其仅清除表单组中的无效表单控件?