I read a integer binary file to int vector. When I use the Sort function the vector is zeroing…
I know the vector is OK!
What could be wrong?
std::ifstream input("D:\\Amostra.txt", ios::binary);
vector<int> v (NumBlocks*ELEMENTS_PER_BLOCK*sizeof(int));
input.read(reinterpret_cast<char *>(&v[0]), NumBlocks*ELEMENTS_PER_BLOCK*sizeof(int));
sort(v.begin(), v.end());
for (int i=0; i<ELEMENTS_PER_BLOCK*NumBlocks; i++){
cout << v[i] << endl;
};
system("pause");
The argument to that constructor is the number of elements you need, not the number of bytes those elements take. This will create
sizeof(int)*Nelements, whereNis the number you need. After sorting the first(sizeof(int)-1)*Nwill be 0.The file has
.txtextension, but you are reading it as if it was binary. If the file is a binary dump, then this read is… well… a code smell but not completely wrong. If the file is text then this is completely wrong.You can read a text file that contains only space separated integers using the
copyalgorithm and aistream_iterator: