lundi 12 octobre 2020

Need to iterate over entire object except for first two elements. Is there a design pattern?

I have a std::vector that I would like to iterate over each object except the first two. A foreach loop would be perfect if I didn't want two . i.e. for(const auto i : items)

Possible solutions I've thought of are erasing the first two and re-adding at the end

const auto firstEle = myVec[0];
const auto secEle = myVec[1];
myVec.erase(myVec.begin());
myVec.erase(myVec.begin());
for(const auto i : items)
{
  //do stuff with i
}
myVec.insert(myVec.begin(), secEle);
myVec.insert(myVec.begin(), firstEle);

or have some sort of flag

unsigned int i = 0;
for(const auto j : items)
{
  if(i < 2)
  {
    i++;
    continue;
   }
   //do stuff with j
}

or use a while loop

unsigned int i = 2;
while(i < myVec.size())
{
  const auto j = myVec[i];
  //do stuff with j

  i++;
}

All these seem more complicated than they need to be. Any better solutions that are simpler?

Aucun commentaire:

Enregistrer un commentaire