1)
And the reason I want to use a vector and set its size dynamically is because I cannot be sure what the length of future files I will be dealing with will be. I would rather write something now that can adapt to larger files without need for rewriting.
Here is a little tip, I/O operations are
always going to be the bottleneck when it comes to efficiency and dynamically allocating memory. Reading the file contents once to count is
not good practice, which is why I am trying to steer you in the right track. Right now you have a small data set. What if you file was 40GB, would you really read it twice, no, you wouldn't even be able to have it cached all at once. You can reserve much more, why not reserve 5000, if files get larger than that then it will allocate for you, it's still not going to be the bottleneck. You don't even need to reserve, just push_back will be much more efficient then reading twice.
2)
If you add a cout line at line 30 from the code above the cout is never reached. |
It wont hit this line because you file is in a state that is not good (because you've already read the entire contents). Sure you seek to the beginning but that doesn't change the state, you have to clear the state to have it read again (having to jump through these hoops to read it again should be
red flags).
3) If you truly want to size the vector and you are in control of the files, you could always make the first line in the file have the count of lines in the file, then
just read that line only. Use the size read in and reserve for the vector, now continue reading and pushing back the rest of the file.
Good luck.