| re: vector of struct ?
sd2004 wrote:[color=blue]
> Coudl someone make the following code more elegant ?
> #include<iostream>
> #include <string>
> #include<vector>
> #include<sstream>
> #include<fstream>
> using namespace std;
>
> struct astruct
> {
> string name;
> int id;
> };
>[/color]
istream& operator >> ( istream& is, const astruct& s )
{
return is >> s.name >> s.id;
}
ostream& operator << ( ostream& os, const astruct& s )
{
return os << s.name << ' ' << s.id;
}
[color=blue]
> int main()
> {
> vector<astruct> v;
> astruct astr;
> astruct* sp;[/color]
Don't declare variables until you can initialize and use them.
[color=blue]
>
> ifstream in ("test5.txt");
> string line;
> while (getline(in,line)){
> istringstream anyname(line);
> anyname>>astr.name>>astr.id;
> v.push_back(astr);
> }[/color]
Try:
vector<astruct> v;
ifstream in ("test5.txt");
astruct astr;
while( in >> astr )
{
v.push_back( astr );
}
[color=blue]
> sp=&v[0];
> for (sp=&v[0];sp->name!="EOT";sp++){
> cout<<"Name : "<<sp->name<<" "<<"ID: "<<sp->id<<endl;
> }[/color]
Get rid of the EOT at the end if you have control over file format, and
then:
copy( v.begin(), v.end(), ostream_iterator<astruct>( cout, "\n" ) );
You'll need to #include <algorithm> and <iterator>.
If you can't change the file format, do this:
typedef vector<astruct>::const_iterator CI;
for( CI i = v.begin(); i != v.end() && i->name != "EOT"; ++i )
{
cout << *i << endl;
}
[color=blue]
> return 0;
>
> }
> ///////////////////////input file =test5.txt
> ///////////////////////////////
> Tom 777
> Idaho 555
> China 111
> Cricket 333
> EOT[/color]
Cheers! --M |