130 likes | 471 Views
Multiset Class and its Iterator. The multiset class is a container class in the Standard Template Library (STL) Include a feature called the iterator , which permits a programmer to easily step through all the elements of an STL container class. Data Structures and Other Objects Using C++.
E N D
Multiset Class and its Iterator • The multiset class is a container class in the Standard Template Library (STL) • Include a feature called the iterator, which permits a programmer to easily step through all the elements of an STL container class. Data Structures and Other Objects Using C++
Multiset and Set classes • Multiset is similar to bag • Set has the same interface as the multiset, except that it stores elements without repetition
Multiset example multiset<int> first; first.insert(8); fisrt.insert(4); first.insert(4); Template instantiation
Multiset restriction • The type of item in a multiset must be possible to compare two items using “<” operator • Satisfy the rules of a strict weak ordering
Multiset members • value_type • size_type • size_type count(const value_type& target) const; • size_type erase(const value_type& target); • size_type size( ) const; • iterator insert(const value_type& entry);
Iterators • An iterator is an object that permits a programmer to easily step through all the items in a container, examining the items changing them. • Member functions: • begin • end • * • ++
begin member function • Its return value is an iterator that provides access to the first item in the container multiset<string> actors; multiset<string>::iterator role; role = actors.begin();
end member function • Its return value is an iterator that provides access to the last item in the container multiset<string> actors; multiset<string>::iterator role; role = actors.end();
* operator • The * operator can be used to access (cannot change) the current element of the iterator multiset<string> actors; multiset<string>::iterator role; role = actors.begin(); cout<< *role <<endl;
++ operator • ++ operator can be used to move an iterator forward to the item in its collection multiset<string> actors; multiset<string>::iterator role; role = actors.begin(); ++role;
Pitfall • Do not access an iterator’s item after reaching end() • Remember end() is one location past the last item of the container
Other multiset operations • != • == • It is an error to compare two iterators from different containers • find • erase multiset<int> m; multiset<int>::iterator position; position = m.find(42); if(position != m.end()) m.erase(position);