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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • efittery
    New Member
    • Jul 2007
    • 1

    #1

    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;

    main()
    {
    ifstream file;
    file.open("test .txt");
    if ( ! file.is_open() )
    {
    cout << "could not open file" << endl;
    exit(1);
    }
    vector<float> numbers ;
    istream_iterato r<float> begin(file), end ;
    copy( begin, end, back_inserter(n umbers) ) ;
    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.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    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:
    Code:
    vector<pair<float, float> > v;
    So you just create a pair, put two floats in there and push onto the vector.

    Comment

    Working...