Reputation: 283
I'm writing a program reading a file containing two values in each line. Those values should be stored in two vectors, xVals and yVals. Therefore I use the push_back-function, but I want my code to be more beautiful. Now it's like:
ifstream file;
file.open("foo.txt");
double TempVal;
while(file >> TempVal){
xVals.push_back(TempVal);
file >> TempVal;
yVals.push_back(TempVal);
}
What I am currently looking for is a solution like this one (just the important line):
while(file >> xVals.push_back(??) >> yVals.push_back(??))
The question marks stand for "I don't know how to get the value passed by ">>" there... Is there an EASY (easier than the three lines above) or nicer way to achieve this? :-)
Thanks
Upvotes: 0
Views: 142
Reputation: 1
Simply to avoid usage of the TempVal
you could operate on the vector instances directly:
while(file.good() && !file.eof())
{
xVals.resize(xVals.size() + 1,0.0);
yVals.resize(yVals.size() + 1,0.0);
file >> xVals.back() >> yVals.back();
}
Upvotes: 0
Reputation: 81349
You could do something like this:
double tempX, tempY;
while( file >> tempX >> tempY )
{
xVals.push_back(tempX);
yVals.push_back(tempY);
}
If you truly wanted something beautiful, you would define a Point
class that performs stream extraction/insertion, and then just use an algorithm:
std::vector<Point> points;
std::copy(
std::istream_iterator< Point >( file ), std::istream_iterator< Point >()
, std::back_inserter( points )
);
Upvotes: 5