简体   繁体   中英

Delete an element from a Vector and move rest of elements down - C++

I have a vector that is of 'simpleVector' :

struct SimpleStruct
{
    XMFLOAT3 hello;
    XMFLOAT3 hi;
};

std::vector <SimpleStruct>      simpleVector(0);

I'm trying to delete an element, such as simpleVector[3], and then move the rest of the elements down one to remove the blank space.

simpleVector.erase(std::remove_if(simpleVector.begin(), simpleVector.end(),
    [](int i) { return i == 3; }), simpleVector.end());

However, I get this error: cannot convert argument 1 from 'SimpleStruct' to 'int'.

Forgive me if this is obvious, I am new to C++. How can I remove this problem?

If you want to remove the element at index 3, you can just do:

simpleVector.erase(simpleVector.begin()+3);

With std::vector , you don't need to explicitly 'move all the other elements down' - it will do that for you after the erase .

The unary predicate passed to std::remove_if needs to be able to accept a SimpleStruct . Its purpose it to evaluate whether each element of the vector should be "removed". Your predicate accepts an int , and there is no conversion from SimpleStruct to int . You need to change your predicate to something that makes sense.

On the other hand, if you want to remove the element at simpleVector[3] , all you need is

simpleVector.erase(simpleVector.begin() + 3);

To remove the element at index 3, do this instead:

simpleVector.erase( simpleVector.begin() + 3 );

Also note that you don't have to worry about moving the rest of the elements down, as the vector handles this for you automatically.

Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list). cplusplus.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM