How do I remove an element of a vector and returning it?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: How do I remove an element of a vector and returning it?

  1. #1
    Join Date
    Dec 2010
    Posts
    648

    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 02:19 AM.

  2. #2
    Join Date
    Oct 2008
    Posts
    1,168

    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.

  3. #3
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,842

    Re: How do I remove an element of a vector and returning it?

    Quote Originally Posted by lucky6969b View Post
    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. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center