The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

stl pop

Is there no way to pop an item from a vector (or any container really) and put it somewhere else? pop_back() destroys the item, and I can't find a way to do what I am trying to do... Help!

ex:

vector<int> ivec(5);
ivec.push_back(10);
ivec.push_back(15);
ivec.push_back(17);

int = ivec.pop_back();  // well doesn't work that way!
stl_newbie
Friday, January 27, 2006
 
 
int i = ivec.back();
ivec.pop_back();

The various pop functions don't return the item removed because it's not possible to write exception-safe code using such an interface. If the pop function returned the removed item and the item's copy constructor threw an exception, the item would be lost no matter what the caller did.
clcr
Saturday, January 28, 2006
 
 
>> int i = ivec.back();
>> ivec.pop_back();

back() returns a reference to the item in the container. If you get a reference with back() and then call pop_back() right after you call back(), wouldn't variable i be referencing something that no longer exists?
stl_newbie
Saturday, January 28, 2006
 
 
Note that it's  'int i = '
Orson Kart
Saturday, January 28, 2006
 
 
"back() returns a reference to the item in the container. If you get a reference with back() and then call pop_back() right after you call back(), wouldn't variable i be referencing something that no longer exists?"

Not unless you assign the return value of back() to a reference, like this:

int &i = ivec.back();

In the example I gave in my previous post, the object referenced by the return value of back() is copied.
clcr
Saturday, January 28, 2006
 
 
> In the example I gave in my previous post, the object
> referenced by the return value of back() is copied.

Ah I see. Thanks!
stl_newbie
Saturday, January 28, 2006
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz