简体   繁体   中英

How to use the penultimate position of an iterator in c++

I have the following piece of code which helps me to write a bunch of values into a comma separated file format. My problem is, that I do not want a comma after the last element written to normcsv . How can I use beg in an If clause of the kind:

if(beg == penultimate element)
then.... bla bla...

Everything I tried out ended up with the iterator being mad invalid

ReadLine.erase(0,17);
int offsets[] = {8,8,8,8,8,8};
boost::offset_separator f(offsets, offsets+6);
boost::tokenizer<boost::offset_separator> RVBEARline(ReadLine,f);
boost::tokenizer<boost::offset_separator>::iterator beg;

for( beg=RVBEARline.begin(); beg!=RVBEARline.end();++beg )
{                                   
    copy=*beg;
    boost::trim(copy);
    if(copy.compare(0,1,".")==0)
    {
        copy.insert(0,"0");
    }

    normcsv << copy <<",";
}

Instead of printing the comma after the element except during the last iteration, print it before the element except during the first iteration. For that, you can use if(beg != RVBEARline.begin()) .

An alternative to ruakh's "first plus rest" approach, you can do with one less local variable by using a loop-and-a-half construct:

{
  auto it = x.begin(), end = x.end();

  if (it != end)
  {
    for ( ; ; )
    {
      process(*it);

      if (++it == end) break;

      print_delimiter();
    }
  }
}

Here x.begin() and x.end() are only called once. There is one mandatory comparison per loop round, the minimum possible. The check for emptiness is hoisted outside.

您不能总是删除最后一个字符,因为您知道这将是多余的逗号吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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