3.3 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:
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.
The behavior of insert() and erase() vary depending on whether the container is sequential or associative. Sequential containers are discussed in the next section.
|