p.magalhaes
p.magalhaes

Reputation: 8374

Sorting Vector in C++

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

Upvotes: 0

Views: 196

Answers (2)

Dan Hulme
Dan Hulme

Reputation: 15290

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.

Upvotes: 3

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 ) );

Upvotes: 12

Related Questions