因此,我想计算输入的.dat文件中一行的元素;大概有几百行,我想将数据存储在二维矢量或数组中,所以我想算出数组应该有多少个“列”。

我目前的想法是,只抓一行,在一个循环中设置一个计数器,然后迭代直到到达该行的末尾,然后将计数器存储的值作为变量推送并初始化数组还有什么,但是,有没有更优雅的解决方案?在我看来,似乎很大量的代码来做某事,这似乎很基础,但我一直无法从搜索中找到更好的东西。

最佳答案

滚动二维矢量(我假设它表示std::vector<std::vector<double> >,并且在数据通常格式正确的假设下(即文件中存在矩形矩阵),我只是将文件逐行解析为向量,然后检查所有行的长度是否相同,在这种情况下,您无需在分配内存之前就算出矩阵的范围,因为每一行都有自己的内存,看起来像这个:

#include <algorithm>
#include <fstream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

std::vector<std::vector<double> > parse_file(std::istream &in) {
  std::string line;
  // istringstream is something you feed a string to read from it like you
  // would from a file or std::cin.
  std::istringstream parser;
  std::vector<std::vector<double>> result;

  while(std::getline(in, line)) {
    parser.clear();
    parser.str(line);

    // read stuff into a vector at the end of the vector vector. The
    // istream_iterators make this easy by making the stringstream accessible
    // like a range of doubles.
    result.emplace_back(std::istream_iterator<double>(parser),
                        std::istream_iterator<double>(      ));
  }

  // check if there are two lines in the matrix that don't have the same
  // length. That would probably be bad. If that would not be bad, omit this.
  if(std::adjacent_find(result.begin(),
                        result.end(),
                        [](std::vector<double> const &lhs,
                           std::vector<double> const &rhs) {
                          return lhs.size() != rhs.size();
                        }) != result.end()) {
    throw std::logic_error("Input file does not contain a rectangular matrix");
  }

  return result;
}

...

std::ifstream in("foo.dat");
auto matrix = parse_file(in);

关于c++ - 计算一条线上的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27455011/

10-10 19:35