0

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");
2
  • 2
    You're casting int to char*. I don't think that's really supposed to work? I are you sure you don't want char instead? Commented Jun 27, 2012 at 20:23
  • Please check the value of NumBlocks Commented Jun 27, 2012 at 20:24

2 Answers 2

12
vector<int> v (NumBlocks*ELEMENTS_PER_BLOCK*sizeof(int));

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)*N elements, where N is the number you need. After sorting the first (sizeof(int)-1)*N will be 0.

input.read(reinterpret_cast<char *>(&v[0]), NumBlocks*ELEMENTS_PER_BLOCK*sizeof(int));

The file has .txt extension, 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 copy algorithm and a istream_iterator:

std::vector<int> v;
v.reserve(NumBlocks*ELEMENTS_PER_BLOCK);
std::copy( std::istream_iterator<int>(input), std::istream_iterator<int>(),
           std::back_inserter( v ) );
Sign up to request clarification or add additional context in comments.

Comments

3

The error's in this line:

vector<int> v (NumBlocks*ELEMENTS_PER_BLOCK*sizeof(int));

The argument should be the number of elements, not the number of bytes, so take out the *sizeof(int) from the end. As it is, your vector has 4 times as many elements as you want. The ones you haven't read into are all zero, so when you call sort, they go to the front of the vector, and then you only print out the zero ones, not the ones with real data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.