从文件中查找多个总和的最有效方法是什么
What is the most efficient way to find multiple sums from a file?
假设我有一个包含多行 3 列的文件:
3 1 3
1 2 3
4 5 6
. . .
目标是找到每列的总和。解决方案很简单:为总和创建 3 个变量,然后再创建 3 个临时变量。
但是,此解决方案不能很好地扩展。如果有 6 列怎么办?然后我必须总共制作 12 个变量。还有其他方法,例如仅创建计数变量和临时变量,并使用计数的模数将临时变量添加到正确的总和中。但这似乎是一个黑客。
有没有更好的方法来做到这一点,或者有一个C++标准库?
为什么不只有一个叫做 sum 的变量和一个叫 temp 的变量。 基本大纲:
Initialize sum to 0;
while there are more lines:
Read 1 line of input till n is found
While line has more inputs:
read each number out of it (using temp)
sum += temp
Next Number
print out sum and reset it to 0
Next Line
您可以使用向量来动态适应列数。向量的每个元素对应于一列的总和。
您可以通过以下方式执行此操作:
#include <iostream>
#include <string> // for using getline()
#include <fstream> // for file reading
#include <sstream> // for line parsing with stringstream
#include <vector> // for vectors
#include <algorithm> // for the output trick
using namespace std;
int main()
{
vector<int> sum; // intiial size is 0
ifstream ifs("test.txt");
string line;
while (getline(ifs, line)) { // read file line by line;
stringstream ss(line); // and parse each line
int input;
for (int i = 0; ss >> input; i++) { // read columns (i counts them)
if (i >= sum.size()) // if there is a new column
sum.resize(i+1); // resize the vector
sum[i]+=input; // in any case update sum of the column
}
}
// when it's finished, just output the result
copy(sum.begin(), sum.end(), ostream_iterator<int>(cout, "; "));
cout << endl;
}
此代码旨在实现完全的灵活性:并非所有行都需要具有相同数量的列(缺少的列仅被视为 0)。
例如,对于文件:
3 5 9 10
2 9 8
7 5 6 7 20
2 4 5 6 8
它将显示:
14; 23; 28; 23; 28;
伪代码:
Open FilePointer (readonly)
create a queue of ints.
create a ptr to queue.
read in a row.
tokenize on space
walk array and push onto ptr the value = value + variable
shift ptr, ptr = ptr->next()
at end of row, shift ptr back to head.
do while not EOF.
walk queue last time, outputing the values.
while(ptr != nullptr) { cout << ptr->value; }
相关文章:
- 映射唯一值和重复值的有效方法.可以访问键或值的位置
- 如何有效地找到数组中三元组和的最小差异?
- C++ - 将函数链接到触发器的有效和高效方法
- 缓存和访问数据库数据的有效方法?
- 带有"up-"和"center-vec3"参数的glm::rotate()的有效替代方案?
- 从另一个向量中搜索和找到元素的有效方法
- 使用for循环制作位图的最简单和最有效的方法
- 无法通过循环运行我的代码,但是手动复制和粘贴有效
- CGAL中的有效k阶voronoi图和三维voronoi图可用于求解
- 在客户端和远程服务器中比较文件列表的有效方法是什么?
- 从C++模拟中保存和加载数据的有效方法
- 什么是ISO14882和ECMA335标准的有效标识符
- 迭代 Java 集合和对元素进行一些转换的有效方法
- 在C++中使用智能指针分配和删除内存的有效方法
- 这是arduino和C++的有效数组吗
- 给定元素数组、子列表的偏移量和长度的有效部分约简
- 顺时针和逆时针旋转阵列的有效方式
- 使用Qt和OpenCV读取和处理视频文件的有效方式
- 构造和传递结构的结构作为函数参数的有效方法
- 从字符[]访问对齐的T和的最有效方法是什么?