[英]Sorting Vector in C++
I read a integer binary file to int vector. 我将一个整数二进制文件读取为int向量。 When I use the Sort function the vector is zeroing...
当我使用Sort函数时,向量将归零...
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");
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. 这将创建
sizeof(int)*N
元素,其中N
是您需要的数字。 After sorting the first (sizeof(int)-1)*N
will be 0. 排序后,第一个
(sizeof(int)-1)*N
将为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. 该文件具有
.txt
扩展名,但您正在读取它,就好像它是二进制文件一样。 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
: 您可以使用
copy
算法和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 ) );
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. 参数应为元素数,而不是字节数,因此从末尾取出
*sizeof(int)
。 As it is, your vector has 4 times as many elements as you want. 实际上,向量具有所需元素的4倍。 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. 您没有读到的那些全为零,因此,当您调用
sort
,它们都位于向量的前面,然后您只打印出零,而不打印具有实际数据的那些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.