简体   繁体   中英

Erasing values from vector/map

Is this a safe way of deleting all entries from my vector or map

Vector

my_vector.erase(my_vector.begin(),my_vector.end());

For example for a map

my_map.erase(my_map.begin(),my_map.end());

The map or vector structure contains elements whose de-allocation is taken care in the destructor of those elements

Does the iterator value returned by end() become invalid as it starts to erase elements?

Both erase() methods are designed to work for iterator ranges excluding the second one.

// erase elements in range [a,b)
Iterator erase(Iterator a, Iterator b);

So it is safe to call erase() as you do, but you might as well call clear() in both cases.

It's safe to call erase(begin, end) for std::vector/std::map , it also valid to other STL containers( list, set, deque etc ) which provide erase member function and iterator to iterate through elements.

As long as you pass in valid range(beg,end), below two ranges are also valid, erase takes no efforts:

c.erase(c.begin(), c.begin());
c.erase(c.end(), clend());

std::vector::erase(beg,end) Removes all elements of the range [beg,end) and returns the position of the next element.

std::map::erase(beg,end) Removes all elements of the range [beg,end) and returns the following position (returned nothing before C++11).


In STL internal implementation, it calls erase(begin,end) in a few functions like:

void clear() noexcept;
Effects: Behaves as if the function calls:
          erase(begin(), end());

void assign(size_type n, const T& t);
Effects:
   erase(begin(), end());
   insert(begin(), first, last);

As you can see, erase(begin(),end()); is the same as clear() .

Alternatively, you could call swap to clear a STL container which is suggested in More Effective STL :

vector<Contestant> v;
vector<Contestant>().swap(v); //clear v and minimize its capacity

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