Efficient way to read from a file?


I'm using this code:

1
2
3
4
5
6
7
8
9
10
void initialize(){
	int temp;

	ifstream x ("Palindroame.txt");
	while(!x.eof()){
		x>>temp;
		myVector.push_back(temp);
	}
	x.close();
}


And I'm wondering if there is a better way of reading from it,withoug using an auxiliar variable,int temp.

// myVector is a vector<int>

Thank you.
Yes, there is indeed a better way to do it:
1
2
3
4
5
6
7
8
9
void initialize(){
	int temp;

	ifstream x ("Palindroame.txt");
	while(x>>temp){
		myVector.push_back(temp);
	}
	x.close();
}
With your code, you get an extra garbage value at the end.

There is not a way to do it without the temporary, though - and if you could, it would probably be less efficient anyway.
Last edited on
Well thanks a lot. This forum is gold.
This is equally efficient, and it avoids placing myVector at namespace scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <vector>
#include <iterator>

std::vector<int> initialize()
{
    std::ifstream file( "palindrome.txt" ) ;
    return { std::istream_iterator<int>(file), std::istream_iterator<int>() } ;
}

int main()
{
   std::vector<int> myVector = initialize() ;
   // ... 
}


I wish I'd known I could do that magic on line 8 in the past :) bookmarking this thread.
closed account (o3hC5Di1)
@JLBorges - Thanks for that, I didn't really know much about the uses of std::istream_iterator. Would you please be so kind as to clarify two things for me?

- return { std::istream_iterator<int>(file), std::istream_iterator<int>() } ; I believe you're constructing a vector here using initializer_list? The reference stated that a default constructed std::istream_iterator holds an end-of-stream state, so at first it would seem like you are saying something like stream.begin() until stream.end(). However, I didn't think initializer_list worked that way for vectors. Could you please clarify?

- myVector.push_back(temp); // from L B's code would using myVector.push_back(std::move(temp)); be another worthwhile optimization here?

All the best,
NwN
Moving primitives is the same as copying them.

http://en.cppreference.com/w/cpp/container/vector/vector See #4

The initializer list overload cannot be selected since it's a vector of ints and not a vector of std::istream_iterator<int>
note, if you want efficiency as in speed (rather than just easy-to-maintain code), there are other ways to read numbers from a file to look at (but only after profiling and determining that this is a bottleneck!): http://www.cplusplus.com/forum/beginner/88679/#msg476690
Topic archived. No new replies allowed.