c++stl

How to detect first or last element iterating over a container?


How to do the following in more stylish/short way?

for(i=container.begin(); i!=container.end(); ++i) {
    if (i!=container.begin()) {
        cout << ", ";
    }
    cout << *i;
    j=i;
    if (++j==container.end()) {
        cout << "!" << endl; 
    }
}

Solutions like foreach are acceptable (actions on first and last elements need to be configurable, though).

P.S. There are many answers that are handling first element, but not last. Here is what I mean by handling last element:

for(i=container.begin(); i!=container.end(); ++i) {
    j=i;
    if (i==container.begin()) {
        cout << "[" << *i << "]" << endl;
    } else if (++j==container.end()) {
        cout << ", (" << *i << ")" << "!" << endl; 
    } else {
         cout << ", " << *i;
    }
}

Don't you think it's very easy to handle first element outside the cycle body? The real problem is the last one! I'm sorry for not being able to clarify the important point asking the question. I think I'll just accept the top ranked answer eventually.


Solution

  • Boost has next / prior which can sometimes help in such situations.

    for(i=container.begin(); i!=container.end(); ++i) {
        if (boost::next(i) == container.end()) {
             std::cout << "!" << std::endl;
        }
    }
    

    Although for this specific case, I'd simply output the first element, loop from second till last while always outputting the ',' and then output the '!' after the loop has ended. (as others have suggested already)

    I don't see the point in moving the special cases inside the loop, and then checking inside the loop for them....