Delete element from C++ array

前端 未结 11 873
逝去的感伤
逝去的感伤 2020-12-11 14:26

Please tell me how to delete an element from a C++ array.

My teacher is setting its value to 0, is that correct?

11条回答
  •  爱一瞬间的悲伤
    2020-12-11 15:06

    You can remove an element from a vector such that the element is no longer there and all the other elements shift a position.

    struct counter
    {
       int x;
       int operator()() { return x++; }
       counter() : x(0) {}
    };
    
    std::vector v;
    std::generate_n( std::back_inserter(v), 8, counter() );
    std::copy(v.begin(), v.end(), std::ostream_iterator(cout, " "));
    std::cout << '\n';
    v.erase( v.begin() + 4 );
    
    std::copy(v.begin(), v.end(), std::ostream_iterator(cout, " "));
    std::cout << '\n';
    

    Should output:

    0 1 2 3 4 5 6 7

    0 1 2 3 5 6 7

    (assume all necessary headers included and main function body etc).

    Note that if you have a vector of pointers which were allocated with new, you would have to possibly call delete on the pointer before it was erased from the vector. (This depends on whether the vector manages the lifetime of these pointers). If you have a vector of boost::shared_ptr you will not need to manage the deletion.

提交回复
热议问题