函数从文件读入向量c++
Function reading from a file into vector C++
我写了一个函数,将未知数量的数据(当在列中)从文件读取到向量。
#include <iostream>
#include <vector>
#include <fstream> // file writing
#include <cassert>
void ReadFromFile(std::vector<double> &x, const std::string &file_name)
{
std::ifstream read_file(file_name);
assert(read_file.is_open());
size_t lineCount = 0;
while (!read_file.eof())
{
double temp;
read_file >> temp;
x.at(lineCount) = temp;
if (lineCount == x.size() - 1) { break; } // fixes the out of range exception
lineCount++;
}
read_file.close();
}
int main()
{
size_t Nx = 7;
size_t Ny = 7;
size_t Nz = 7;
size_t N = Nx*Ny*Nz;
// Initial Arrays
std::vector <double> rx(N);
std::string Loadrx = "Loadrx.txt";
ReadFromFile(rx, Loadrx);
}
但是lineCount会在文件中的数据被复制到vector之后再增加一次。有没有比我写的if语句更优雅的方法来解决这个问题?
我写了一个函数,读取一个未知的数量的数据(当在一个列中)从一个文件到一个向量。
从"列"(或其他规则格式化的)文件中读取未知数量数据的最优雅(我认为也是最惯用的)方法之一是使用istream迭代器:
void ReadFromFile(std::vector<double> &x, const std::string &file_name)
{
std::ifstream read_file(file_name);
assert(read_file.is_open());
std::copy(std::istream_iterator<double>(read_file), std::istream_iterator<double>(),
std::back_inserter(x));
read_file.close();
}
用法:
int main()
{
// Note the default constructor - we are constructing an initially empty vector.
std::vector<double> rx;
ReadFromFile(rx, "Loadrx.txt");
}
如果你想写一个"安全"的版本,读取的元素数量有限,使用copy_if
:
void ReadFromFile(std::vector<double> &x, const std::string &file_name, unsigned int max_read)
{
std::ifstream read_file(file_name);
assert(read_file.is_open());
unsigned int cur = 0;
std::copy_if(std::istream_iterator<double>(read_file), std::istream_iterator<double>(),
std::back_inserter(x), [&](const double&) {
return (cur++ < max_read);
});
read_file.close();
}
用法明显:
ReadFromFile(rx, Loadrx, max_numbers);
尝试:
void ReadFromFile(const size_t N,
std::vector<double> &x,
const std::string &file_name)
{
std::ifstream read_file(file_name);
assert(read_file.is_open());
while (true)
{
double temp;
read_file >> temp; // read something
if(read_file.eof()) break; // exit when eof
x.push_back(temp);
if (N == x.size()) break; // exit when N elements
}
read_file.close();
}
int main()
{
size_t N = 10;
std::vector<double> v;
v.reserve(N);
ReadFromFile(v,"Data.txt");
}
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么