There are other containers that can provide you with all that you seek to do. A set or multiset container for instance will allow you to erase specific elements using either an iterator or a copy of the element you wish to search for. It will also automatically sort the elements you add to it, provided you tell it how the elements should be ordered by implementing the less-than operator. A set will only store unique elements while a multiset can be used to store many elements with the same value. As an example:
Code:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
#include <set>
class person
{
public:
std::string name;
// Constructors
person() {}
person(const std::string& rhs) { name = rhs; }
// Friend operators
friend bool operator<(const person& lhs, const person& rhs);
friend std::ostream& operator<<(std::ostream& os,const person& rhs);
};
//Friend insertion operator, needed to make "copy" work properly
std::ostream& operator<<(std::ostream& os,const person& rhs)
{
return os << rhs.name;
}
//Friend less-than operator, needed to make "erase" and
//automatic sorting work properly
bool operator<(const person& lhs, const person& rhs)
{
return lhs.name < rhs.name;
}
int main()
{
std::set<person> strSet;
strSet.insert(person("Robert"));
strSet.insert(person("Johnson"));
strSet.insert(person("Albert"));
std::cout << "Before erasing Johnson: ";
std::copy(strSet.begin(),strSet.end(),
std::ostream_iterator<person>(std::cout," "));
// Provide a copy of element "Johnson" to the erase function
strSet.erase(person("Johnson"));
std::cout << "\nAfter erasing Johnson : ";
std::copy(strSet.begin(),strSet.end(),
std::ostream_iterator<person>(std::cout," "));
std::cout << std::endl;
return 0;
}
This should output:
Code:
Before erasing Johnson: Albert Johnson Robert
After erasing Johnson : Albert Robert
As you can see, even though the elements were inserted in reverse alphabetical order, the set container automatically sorted them properly because that is how I implemented the less-than operator in this case.
If it looks like the copy function and overloading of the insertion operator is too confusing for you, they can be removed and a more conventional looping mechanism can be used to output the contents of the set container to the screen... but you do need the less-than operator to define how the elements are to be sorted.