【问题标题】:Counting the elements on a line计算一行中的元素
【发布时间】:2015-02-11 20:02:44
【问题描述】:

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

我目前的想法是,只抓取一行,在循环中设置一些计数器,然后迭代直到到达行尾,然后将计数器存储的值作为变量推送,然后初始化数组等等,但是,有没有更优雅的解决方案?做某事似乎需要相当多的代码,对我来说,这似乎很基本,但我无法通过四处搜索找到更好的东西。

【问题讨论】:

  • 所以你的目标是将每一行放入一个数组/向量中?

标签: c++ arrays string iterator


【解决方案1】:

滚动二维向量(我假设这意味着 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);

【讨论】:

  • 哈哈,这看起来很棒。谢谢你。将其称为 2D 矢量或其他什么是不正确的?
  • 不,没有错。只是这个术语是模棱两可的——它也可能意味着你以某种方式寻址的平面向量,例如(即镜像 2D 数组是什么)。
  • 明白。再次感谢您的帮助。
猜你喜欢
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2021-01-01
  • 1970-01-01
  • 2015-04-18
相关资源
最近更新 更多