[prog] C++ - linked list and segmentation fault

Robert J. Hansen rjh at sixdemonbag.org
Tue Apr 8 13:32:20 EST 2003


> Personally, I think it's good to help students with questions about course
> work but you aren't doing them any favors if you write it for them.

Oh, heavens no--if that's the impression which I gave, it was sorely in
error.  When I said "I'll ... show you how to use the built-in C++ list
class to do what you want done," I certainly didn't mean to imply I'd be
presenting a full solution: my aim is to show a clean and efficient
method of approaching the problem, nothing more.  Show her how to do
what she wants done--not actually do it for her.  :)

=====

// iostream and fstream are necessary header files for disk I/O.
#include <iostream> 
#include <fstream>

// list is the header file which declares a linked list:
#include <list>

// and iterator is the header which gives us istream/ostream iterators:
#include <iterator>

// and here's where our copy algorithm is held.
#include <algorithm>

using std::list;
using std::copy;
using std::ifstream;
using std::ofstream;
using std::istream_iterator;
using std::ostream_iterator;

int main()
{
    // Create a linked list of type int.  Right now it's naked (i.e.,
    // has no data).

    list<int> mylist;

    // Open our input and output files appropriately...

    ifstream in("data.txt");
    ofstream out("data-output.txt");

    // Copy takes three iterator arguments: the beginning and end of
    // the sequence you want to copy, and where you want to copy them
    // to.  With this first call, we're copying them from an input
    // filestream (hence our use of input_iterators).  SEE: Stroustrup,
    // section 19.2.6 (pg 559 in the 3rd Edition); alternately,
    // see Josuttis, section 9.6 (pg 363 in my copy).

    copy(istream_iterator<int>(in), istream_iterator<int>(),
	 back_inserter(mylist));

    // And here we do likewise, but with an output sequence.

    copy(mylist.begin(), mylist.end(), ostream_iterator<int>(out, " "));

    // main() _always_ returns a value.  If you don't include one, it'll
    // default to returning a 0.  It's a good habit to get into, though,
    // to do it yourself.

    return 0;
}

=====

... Once you discard the scaffolding (the includes and usings, the int
main()/return 0, and brackets), you've got six lines of code which show
how easy it is to create and use linked lists in C++, and how to use
them to do I/O which would take many dozens of lines in C.

-- 
Robert J. Hansen <rjh at sixdemonbag.org>



More information about the Programming mailing list