简体   繁体   English

来回迭代模式

[英]Iteration pattern forth and back

I'm trying to go through a list where n is the length of the list the pattern would be the first element, n, second element, n-1, the third element, n-2...我正在尝试 go 通过一个列表,其中 n 是列表的长度,模式将是第一个元素 n,第二个元素,n-1,第三个元素,n-2 ...

how is this possible?这怎么可能?

You'd generally use two indices and repeat what needs to be done twice:您通常会使用两个索引并重复需要做的事情两次:

for (int lo = 0, hi = n - 1; hi <= lo; ++lo, --hi) {
  doStuff(list.get(lo));
  if (lo == hi) break;  // don't handle a middle element twice.
  doStuff(list.get(hi));
}

If you really need a bouncing single index, that's possible but ugly:如果你真的需要一个跳动的单一索引,那是可能的但很难看:

for (int d = 0; d < n; ++d) {
  int i = (d & 1) == 0 ? (d / 2) : (n - 1 - (d / 2));
  doStuff(list.get(i));
}

If this is a common operation, you'd want to define an Iterator that hides the ugliness.如果这是一个常见的操作,你会想要定义一个隐藏丑陋之处的Iterator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM