correct idiom for container

K

keith

Is the following code well-formed and portable?

Value value;
Container<Value> c;

c.push_back(value);
c.erase(--c.end());

Container can be std::string, std::vector...
 
J

Jonathan Lee

It's not quite that simple. If the iterator is a class type you can
decrement it. So if the iterator isn't a class type, the code is
ill-formed; if the iterator is a class type, the code works fine. But
it's not portable.

Using rbegin() instead of --end() should fix that.

--Jonathan
 
J

James Kanze

It's not quite that simple. If the iterator is a class type you can
decrement it.

Maybe. If the iterator is a class type and the increment
operator is a member, you can decrement it. If the increment
operator is a free function, taking the iterator as a non-const
reference, you can't. (I don't know of any implementations
which do it that way, but I don't know why. It's the way I'd do
it.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top