 • Print
This chapter is from the book

Operations Common to All Containers

The following operations are common to all the container classes (as well as the string class):

• The equality (==) and inequality (!=) operators return true or false.

• The assignment (=) operator copies one container into another.

• empty() returns true if the container holds no elements.

• size() returns a count of the elements currently held within the container.

• clear() deletes all the elements.

• The following function exercises each of these operations:

```void comp( vector<int> &v1, vector<int> &v2 )
{
// are the two vectors equal?
if ( v1 == v2 )
return;
// is either vector empty?
if ( v1.empty() || v2.empty() ) return;

// no point defining it unless we are going to use it!
vector<int> t;

// assign t the largest vector
t = v1.size() > v2.size() ? v1 : v2;

// ... use t ...

// ok. empty t of its elements
// t.empty() will now return true
// t.size() will now return 0
t.clear();

// ... ok, fill up t and use it some more ...
}```

Each container supports a begin() and an end() operation to return, respectively, an iterator to the first element of the container and 1 past the last valid element:

• begin() returns an iterator to the first element.

• end() returns an iterator that addresses 1 past the last element.

Typically, we iterate across a container starting at begin() and stopping when we reach end(). All containers support an insert() operation to add elements and an erase() operation to delete elements.

• insert() adds one element or a range of elements to a container.

• erase() deletes one element or a range of elements from a container.

The behavior of insert() and erase() varies depending on whether the container is sequential or associative. Sequential containers are discussed in the next section.