nog said:
Thanks for responding Jeff, although with my very limited
repertoire, this doesn't translate into a solution for me.
None of the vector examples I've looked at deal with
accommodating data of differing types in a row x column
fashion so, unfortunately it doesn't get me too far.
I've got several lines of data:
name1, address1, date1
name2, address2, date2,
... etc.
and I want to use these to instantiate objects via the
constructor. All of this is quite new to me so seeing your
suggestion hasn't instantly lit any fires.
using namespace std; // just for clarity
struct Datum
{
string name1;
string address1;
string date1;
};
Then
vector<Datum> table;
Will create a variable-sized array of Datum objects. If you actually
want to initialize them at compile time with fixed values, that can be
done neatly by adding a constructor:
using namespace std;
struct Datum
{
Datum() { } // need this for vector<>
Datum(const string& name, const string& addr, const string& date) :
name1(name), address1(addr), date1(date) { }
string name1;
string address1;
string date1;
};
And do something like:
table.push_back(Datum("Mr Joe Bloggs", "4 City Rd", "5/10/1946"));
table.push_back(Datum("Mrs Jane Brown", "2/34 High St",
"7/3/1958"));
etc. etc.
But more likely you'd want to read these from a file, or from user
input, and how you do this depends largely on what file format you
want to use. However if you can write a function like this:
istream& operator>>(istream& stream, Datum& datum)
{
// read in the members - very trivial possibility is:
stream >> datum.name1 >> datum.address1 >> datum.date1;
return stream;
}
Then you can read in the whole vector like this:
(#include <iterator>)
void read_table(istream& stream, vector<Datum>& table)
{
table.insert(table.end(), istream_iterator<Datum>(stream),
istream_iterator<Datum>());
}
Unfortunately some older compilers won't support that last call to
insert - you could also try:
#include <algorithm>
void read_table(istream& stream, vector<Datum>& table)
{
copy(istream_iterator<Datum>(stream), istream_iterator<Datum>(),
inserter(table, table.end()));
}
Note that std::vector<> isn't very efficient for adding large amounts
of data to, unless you can roughly guess its likely maximum size
beforehand (and use reserve()). Other alternatives are std::list<>
and std::deque<>.
Hope this doesn't scare you off too much, but learning how to use the
standard containers, streams and algorithms to do basic everyday tasks
is vital to understanding the power of C++.
Dylan