1

Is it possible to resize without initializing (just like reserve, but also set the size of the vector).

The following code reads a binary file and put it in a uint32_t vector.. The code uses reserve and use the capacity (instead of size) to store the number of elements in the vector. This seems awkward.

#include <iostream>
#include <vector>
#include <fstream>
#include <byteswap.h>
#include <iterator>
#include <cassert>

using namespace std;

//typedef unsigned char BYTE;
//typedef double BYTE;
template <typename T>
std::vector<T> readFile(const char* filename){
    assert(sizeof(char) == 1);
    // open the file:
    std::ifstream file(filename, std::ios::binary);

    // Stop eating new lines in binary mode!!!
    file.unsetf(std::ios::skipws);

    // get its size:
    std::streampos fileSize;

    file.seekg(0, std::ios::end);
    fileSize = file.tellg();
    file.seekg(0, std::ios::beg);

    // reserve capacity

    std::vector<T> vec;
    cout << "reserved: " << fileSize*sizeof(unsigned char)/sizeof(T) << endl;
    vec.reserve(fileSize*sizeof(unsigned char)/sizeof(T));
    unsigned char* ptr_vec = (unsigned char*) vec.data();

    typedef std::istream_iterator<unsigned char> streamiter;
    int i = 0;
    cout << "data in vector1: " << endl;
    for (streamiter it = streamiter(file); it != streamiter(); it++) {
        ptr_vec[i] =  *(it);
        cout << int(ptr_vec[i]) << ' ';
        ++i;
    }
    cout << endl;
    cout << "data in vector; " << endl;
    cout << endl;
    for (i=0;i<vec.capacity();i++){
        cout << int(vec[i]) << ' ';
    }

    return vec;
}


int main(void){
    std::vector<uint32_t> arr = readFile<uint32_t>("test.bin");
}  
rxu
  • 1,369
  • 1
  • 11
  • 29

0 Answers0