Gwar said:
// What about for dealing with matrices?
#include <vector>
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <sstream>
using namespace std;
void parse(string& s, int& n, vector<int>& nv);
void display(vector <int>& v);
int main()
{
ifstream ifs("ints.dat");
string s;
vector<int> v;
vector< vector<int> > vm;
int n;
int i = 1;
while(getline(ifs, s, '\n'))
{
parse(s, n, v);
vm.push_back(v);
v.erase(v.begin(), v.end());
}
for_each(vm.begin(), vm.end(), display);
}
void parse(string& s, int& n, vector<int>& v)
{
istringstream ss(s);
while(ss >> n)
v.push_back(n);
}
void display(vector <int>& v)
{
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
That works just fine. My solution for this problem is very similar, only
that my parse function looks like the following:
////////////////////////////////////////////////////////////////////////////
//
template <class T>
std::vector<T> StringToVec( const std::string& Str )
// Tokenize a passed line/string into a vector
// e.g:
// std::string str = "1 2 3 4";
// std::vector<int> vec = StringToVector<int>(str);
////////////////////////////////////////////////////////////////////////////
//
{
std::vector<T> MyVec;
copy( std::istream_iterator<T>( std::istringstream( Str ) ),
std::istream_iterator<T>(), back_inserter(MyVec) );
return MyVec;
}
Of course one could pass the vector as a parameter & hence save unnecessary
copies (which might be optimized by the compiler anyway). If your compiler
supports it (MSVC 6 for example doesn't!) you can save yourself the copy
statement and pass the istream_iterators to the ctor of the vector.
Cheers
Chris