Using the C++ Standard Template Libraries (STL) can be easy, once you know how to do it. No need to putz around with doubly linked lists anymore! Here is code showing how a STL list allows you to add, insert, remove, sort, splice, merge, display, and clean-out-duplicate strings.
Experimenting with the STL list
// manipulate strings in a list
// using list from the Standard Template Libraries
// list is just a very generic doubly linked list and
// therefore allows for fast insertions and deletions
// a Dev-C++ tested Console Application by vegaseat 28nov2004
#include <iostream>
#include <list> // stl header
#include <iterator> // ostream_iterator
static char names[8][10]=
{
"Heidi", "Bertha", "Samantha", "Rubin",
"Frank", "Sandy", "Sunny", "Rubin"
};
static char norge[6][10]=
{
"Jens", "Hildegard", "Bjorn", "Ulla", "Joerg", "Mila"
};
using namespace std; // std::cout
int main()
{
int k;
list<string> sL;
// load the list
// push_back appends strings to the end of a list
for(int k = 0; k < 8; k++)
{
sL.push_back(names[k]);
}
cout << "contents of the list in order:\n";
// print out the list one item on a line
copy(sL.begin(),sL.end(),ostream_iterator<string>(cout,"\n"));
// sort the list
sL.sort();
cout << "sort the list:" << endl;
copy(sL.begin(),sL.end(),ostream_iterator<string>(cout,"\n"));
// remove all instances of Frank from the list
sL.remove("Frank");
cout << "remove Frank from the list:\n";
copy(sL.begin(),sL.end(),ostream_iterator<string>(cout,"\n"));
// add Karl to the beginning of the list
sL.push_front("Karl");
cout << "add Karl to the beginning of the list:\n";
copy(sL.begin(),sL.end(),ostream_iterator<string>(cout,"\n"));
// add Zoe as the third item in the list
list<string>::iterator iter1; // pointer to list items
iter1 = sL.begin(); // point to first item in list
iter1++; // point to second item
iter1++; // point to third item
sL.insert(iter1,1,"Zoe"); // insert Zoe one time
cout << "insert Zoe as third item in list:" << endl;
copy(sL.begin(),sL.end(),ostream_iterator<string>(cout,"\n"));
// remove duplicate items
sL.unique();
sL.sort(); // sort again
cout << "remove any duplicates and sort again:" << endl;
copy(sL.begin(),sL.end(),ostream_iterator<string>(cout,"\n"));
// this shows a different way to initialize a list with an array
list<string> nL(norge, norge+6);
// you made some friends on your last trip to Norway
// and want to append their names to your present list
// splice() merges the two lists without sort
// you can use sL.merge(nL) to merge the two lists with sort
sL.splice(sL.end(), nL);
cout << "splice norge list to end of name list:" << endl;
copy(sL.begin(),sL.end(),ostream_iterator<string>(cout,"\n"));
cin.get(); // wait
return 0;
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.