获取迭代器的位置??C++

Get the position of the iterator?? C++

本文关键字:C++ 位置 迭代器 获取      更新时间:2023-10-16

需要检查位置是奇数还是偶数。

 for(auto a : aliens) {
  if(a - vec.begin() % 2 == 0){
   /*do something */ 
  }

从我所研究的内容中猜测它会是类似的东西,但似乎无法让它运行,这很烦人。谢谢。。

更简单的方法:

bool isEven = true;
for(auto a : aliens) {
  isEven = !isEven;
  if(isEven){
   /*do something */ 
  }
实际上你不能

在这种类型的循环中做到这一点。这是foreach的,foreach 它不允许您访问迭代器,而是访问迭代对象本身。当您需要访问迭代器时,您必须使用for循环。