468,783 Members | 1,599 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,783 developers. It's quick & easy.

initializing in memory vector of floats from file with no apriori knowledge of size

I need to modify the following code to handle a
vector of pairs of floats. I was just thinking of casting
my vector of floats into being a vector of pairs of floats.

Alternately, I have looked into using the instream iterator
to initialize the vector of pairs of floats.

Any thoughts would be appreciated.

given the test.txt file which contains:

1.2 3.4
3.2 4.5
8.3 8.1
3.2 1.2
3.3 8.8

and the source code z.cpp:

#include <vector>

#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <assert.h>

using namespace std;

ifstream file;
if ( ! file.is_open() )
cout << "could not open file" << endl;
vector<float> numbers ;
istream_iterator<float> begin(file), end ;
copy( begin, end, back_inserter(numbers) ) ;
cout << "Size of array is: " << numbers.size() << endl;
assert( file.eof() ) ;

type "make z"

then type ./z

and you should see "Size of array is: 10"

So this code reads a file with ascii text that
happens to be rows containing pairs of floats.
It then initializes an in memory vector with the
values found. It does this without knowing how
many values are in the file. By adding enough lines
with more values, you can get the message
"Size of array is: 10000". I didn't put any code in
to make sure I have enough memory.
Oct 5 '08 #1
1 1601
9,207 Expert Mod 8TB
You won't be able to make a cast like that. Besides, this is C++ and you should not be casting like it was C.

You said it yourself: pairs of floats:
Expand|Select|Wrap|Line Numbers
  1. vector<pair<float, float> > v;
So you just create a pair, put two floats in there and push onto the vector.
Oct 5 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

11 posts views Thread by Michael B. Allen | last post: by
1 post views Thread by Riadh Elloumi | last post: by
16 posts views Thread by Emanuel Ziegler | last post: by
3 posts views Thread by eriwik | last post: by
15 posts views Thread by syang8 | last post: by
12 posts views Thread by mast2as | last post: by
1 post views Thread by liuhaoran | last post: by
6 posts views Thread by zacariaz | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
2 posts views Thread by Marin | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.