-
September 22nd, 2014, 12:06 AM
#1
How do I remove an element of a vector and returning it?
pop_back just returns void, so I just can't use that?
erase is okay but it doesn't return anything....
Do I use a combination of both?
Thanks
Jack
Last edited by lucky6969b; September 22nd, 2014 at 01:19 AM.
-
September 22nd, 2014, 01:59 AM
#2
Re: How do I remove an element of a vector and returning it?
if "it" is an iterator referring to the to be removed element, "v" is the vector and "T" its value_type:
Code:
// 1)
// requires T to be copyable
// will make v copy all elements after "it", order is preserved
T elem = *it;
v.erase(it);
// 2)
// requires T to be copyable
// no more copy, order is not preserved
using std::swap;
T elem = *it;
swap( *it, v.back() );
v.pop_back();
if T is only movable, just replace elem initializations above with a move.
-
September 22nd, 2014, 03:32 AM
#3
Re: How do I remove an element of a vector and returning it?
Originally Posted by lucky6969b
pop_back just returns void, so I just can't use that?
erase is okay but it doesn't return anything....
Do I use a combination of both?
Thanks
Jack
As you state, pop_back just deletes the last element and doesn't return anything. If you want the contents of the last element before you delete it then use back() before pop_back(). See http://www.cplusplus.com/reference/vector/vector/back/
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|