如何在c++中有效地读取新行分隔的整数
How to read new line separated integers efficiently in C++?
我需要从文件中读取一个大的整数列表,但在时间方面尽可能高效。整数用换行符分隔。我猜使用cin一次读取一个整数会导致非常频繁的读取。
我猜一次读取多个整数会加快速度!但是怎么做呢?
编辑:我使用了重定向到stdin的文件。所以我用cin读取整数您可以使用stl
来尝试此代码std::ifstream myFile("TheNameOfYourFile");
std::list<int> myList;
int number;
while (myFile >> number)
{
myList.push_back(number);
}
从硬件的角度来看,你不能只读取几个字节-你读取整个扇区到内存中,下一个扇区是缓冲的,而你使用fstream
读取它们(我猜你在写cin
时正在考虑fstream
…)。
stringstream
而不是string
。
http://www.boost.org/doc/libs/1_48_0/libs/spirit/example/lex/example.hpp 如果您需要最佳性能:
- 从ASCII字符串解析整数比读取二进制数据慢。
-
iostream
IO比stdio.h
IO慢得多。
从二进制文件/stdin中读取nitems
整数到数组中:
#include <stdio.h>
#include <stdlib.h>
int main() {
// first read number of integers in the array
size_t nitems = -1;
if (fread(&nitems, sizeof(nitems), 1, stdin) != 1) {
perror("nitems");
exit(EXIT_FAILURE);
}
// allocate memory for the array
int *arr = (int*) malloc(nitems*sizeof(*arr));
if (arr == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
// read integers
size_t n = fread(arr, sizeof(*arr), nitems, stdin);
if (n != nitems) {
perror("fread");
exit(EXIT_FAILURE);
}
// do something with `arr` here
for (int* a = arr; a != &arr[nitems]; ++a)
printf("%dn", *a);
exit(EXIT_SUCCESS);
}
将行分隔的整数转换为有效的二进制格式:
#include <cstdio>
#include <iostream>
#include <vector>
int main() {
using namespace std;
// read integers from ascii file/stdin
int i = -1;
vector<int> v;
while (cin >> i) v.push_back(i);
if (v.size() == 0) return 2;
// write the array in binary format
size_t nmemb = v.size();
if (fwrite(&nmemb, sizeof(nmemb), 1, stdout) != 1 ||
fwrite(&v[0], sizeof(v[0]), nmemb, stdout) != nmemb) {
cerr << "failed to write the arrayn";
return 1;
}
}
缺点是不可移植:sizeof(int)
和/或尾端对齐在不同的操作系统上可能不同。
转换成二进制格式的整数存储在array.txt
:
$ g++ convert-to-bin.cc -o convert-to-bin &&
< array.txt ./convert-to-bin >array.bin
之后,你可以有效地从array.bin
中读取整数:
$ g++ read-integer-array.cc -o read-integer-array &&
< array.bin ./read-integer-array
以上假设需要多次从文件中读取整数。
相关文章:
- 使用新行和不使用新行读取文件
- 如何将 txt 文件中的行分隔为组件C++
- 无法通过空白将文本文件行分隔为矢量
- 遇到新行时,有没有办法停止istream_iterator
- PangoLayout 中忽略的新行
- 使用 clang 格式时,当行很大时,如何将右括号分成新行?
- 如何检测将文本文件读入 int 数组的新行
- 当 getline 直到新行才读取时会发生什么?
- 添加新行时工作代码引发异常.调试技巧?
- QTree查看新行,没有布局就不可见已更改
- 嵌套结构,从由空行分隔的文件中读取数据
- 新行上的 clang 格式右括号
- C++流:保存到新行而不是覆盖旧行
- (C++) 使用诅咒打印从文件中读入的新行
- 按升序输出整数时,将最后一个整数放在新行上
- 用C++计算输入文本的新行数
- 在C++中打印用新行分隔的6,5,4,3,2个字符
- c++将行getline放入数组中,用新行分隔
- 如何在c++中有效地读取新行分隔的整数
- c++从文件中读取用空格和新行分隔的单词