std :: vector调整大小而不初始化

时间:2016-07-13 22:43:51

标签: c++ vector

是否可以在不初始化的情况下调整大小(就像保留一样,但也可以设置向量的大小)。

以下代码读取二进制文件并将其放在uint32_t向量中。代码使用reserve并使用容量(而不是大小)来存储向量中的元素数。这看起来很尴尬。

#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");
}  

0 个答案:

没有答案