Delete element from C++ array

前端 未结 11 889
逝去的感伤
逝去的感伤 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 14:56

    1) If you have an array of pointers, then like this :

    // to create an array :
    std::vector< int* > arr( 10, NULL );
    for ( std::vector< int* >:iterator it=arr.begin; arr.end() != it; ++ it )
    {
      *it = new int( 20 );
    }
    // to delete one element
    delete( arr.at(3) );
    

    Any access to this array element is formally an undefined behaviour by the c++ standard. Even assignment of NULL, like this:

    arr.at(3) = NULL;
    

    2) If you really must use pointers, then use smart pointers (this specific case requires shared_ptr) :

    std::vector< std::shared_ptr< int > > arr;
    

提交回复
热议问题