Friday, January 1, 2010

STL LIST - clear(), sort() and unique()

clear():
void clear ( );
Clear content

All the elements in the list container are dropped: their destructors are called, and then they are removed from the list container, leaving it with a size of 0.

// clearing lists
#include
#include
using namespace std;

int main ()
{
list mylist;
list::iterator it;

mylist.push_back (100);
mylist.push_back (200);
mylist.push_back (300);

cout << "mylist contains:";
for (it=mylist.begin(); it!=mylist.end(); ++it)
cout << " " << *it;

mylist.clear();
mylist.push_back (1101);
mylist.push_back (2202);

cout << "\nmylist contains:";
for (it=mylist.begin(); it!=mylist.end(); ++it)
cout << " " << *it;

cout << endl;

return 0;
}

Output:
mylist contains: 100 200 300
mylist contains: 1101 2202


sort():

Sort elements in container.
Sorts the elements in the container from lower to higher. The sorting is performed by comparing the elements in the container in pairs using a sorting algorithm.

int main ()
{
list mylist;
list::iterator it;
mylist.push_back ("one");
mylist.push_back ("two");
mylist.push_back ("Three");

mylist.sort();

cout << "mylist contains:";
for (it=mylist.begin(); it!=mylist.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
Output:
mylist contains: Three one two

For default strings, the comparison is a strict character code comparison, where all uppercase letters compare lower than all lowercase letters, putting all strings beginning by an uppercase letter before in the first sorting operation.



unique():
Remove duplicate values

int main ()
{
double mydoubles[]={ 12.15, 2.72, 73.0, 12.77, 3.14,
12.77, 73.35, 72.25, 15.3, 72.25 };
list mylist (mydoubles,mydoubles+10);

mylist.sort(); // 2.72, 3.14, 12.15, 12.77, 12.77,
// 15.3, 72.25, 72.25, 73.0, 73.35

mylist.unique(); // 2.72, 3.14, 12.15, 12.77
// 15.3, 72.25, 73.0, 73.35
cout << "mylist contains:";
for (list::iterator it=mylist.begin(); it!=mylist.end(); ++it)
cout << " " << *it;
cout << endl;

return 0;
}

Output:
mylist contains:2.72, 3.14, 12.15, 12.77, 15.3, 72.25, 73.0, 73.35

No comments:

Post a Comment