【问题标题】:finding max in bunch of arrays in C在C中的一堆数组中找到最大值
【发布时间】:2011-03-08 23:20:12
【问题描述】:

我有几个问题。 我有一个包含这些信息的文本文件

x0,x1,y0,y1
142,310,0,959
299,467,0,959
456,639,0,959
628,796,0,959
  1. 首先,我想使用fscanf 读取文本文件,并通过跳过第一行仅将数字放入4 个数组c1c2c3c4。所以最终的结果是

    c[1] = {142, 310, 0, 959}
    c[2] = {299, 467, 0, 959}
    c[3] = {456, 639, 0, 959}
    c[4] = {628, 796, 0, 959}
    
  2. 然后,对于每个c[1]c[4],我想找到最大整数并将其存储在 [x, y] 数据类型中。因此,例如在c[1] 中,最大值将为max[1] = [310, 959]。

有人可以帮忙吗?也欢迎使用数组以外的其他 C 解决方案来解决此问题。

在matlab中,代码是

fid = fopen('foo.txt','r');
c = textscan(fid,'%d%d%d%d','delimiter',',','headerlines',1);
fclose(fid);

这将简单地忽略第一行,然后将其余数字复制到 matlab 中的数组中。 我想把这段代码翻译成C。 非常感谢。

【问题讨论】:

  • 我可以帮忙,把你的代码贴出来,我看看。
  • 嗯,为什么要在最大值中包含 2 个值?
  • 将值存储到 STL 向量中并对其进行排序。那么最后两个元素将是您的最大值。
  • 你如何定义你的关系~?这是否意味着大小相似?
  • 您仍然没有粘贴任何代码来尝试读取文件,您是否正在执行以下操作:readline(fp);while(!feof(fp)){row++; fscanf ("%f,%f" .., &c[row][0],&c[row][1], ..) }; ..

标签: c++ arrays matlab scanf


【解决方案1】:

虽然不能直接满足您的问题,但我提供了一个使用structstd::istreamstd::vector 的阅读点示例。这些优先于 fscanf 和数组。

struct Point
{
  unsigned int x;
  unsigned int y;

  friend std::istream& operator>>(std::istream& inp, Point& p);
};

std::istream& operator>>(std::istream& inp, Point& p)
{
  inp >> p.x;
  //Insert code here to read the separator character(s)
  inp >> p.y;
  return inp;
}

void Read_Points(std::istream& input, std::vector<Point>& container)
{
  // Ignore the first line.
  inp.ignore(1024, '\n');

  // Read in the points
  Point p;
  while (inp >> p)
  {
     container.push_back(p);
  }
  return;
}

Point 结构提供了更高的可读性,恕我直言,更通用,因为您可以使用 Point 声明其他类:

class Line
{
  Point start;
  Point end;
};

class Rectangle
{
  Point upper_left_corner;
  Point lower_right_corner;
  friend std::istream& operator>>(std::istream& inp, Rectangle& r);
};

您可以使用operator&gt;&gt; 来添加从文件中读取的方法:

std::istream& operator>> (std::istream& input, Rectangle& r)
{
  inp >> r.upper_left_corner;
  //Insert code here to read the separator character(s)
  inp >> r.lower_left_corner;
  return inp;
}

数组是个问题,可能会导致严重的运行时错误,例如缓冲区溢出。将std::vector、类或结构优先于数组。

另外,由于使用了std::istream,这些结构和类可以很容易地与std::cin 和文件(std::ifstream)一起使用:

  // Input from console
  Rectangle r;
  std::cin >> r;

【讨论】:

  • 我同意你的说法,但我不确定这段代码将如何适应 OP 的用例,即一次读取两点并从最大值 X 和最大值中得出一个点Y 两点。另外,请考虑container.insert(container.begin(), std::istream_iterator&lt;Point&gt;(input), std::istream_iterator&lt;Point&gt;()),而不是while(inp&gt;&gt;p) {...}。 (我可能在其中留下了所需的类型名,您可能需要额外的括号以避免解析器将 istream_iterator 表达式解析为函数声明/指针而不是临时对象。
【解决方案2】:

以防万一

也欢迎使用其他格式来解决此问题。

也表示其他语言,解决这个问题的Python代码会是这样的

fo = open('a.txt','r')
line = fo.readline() #ignore first line
max = [sorted(map(int,line.split(',')))[-2:] for line in fo]

结果是

[[310, 959], [467, 959], [639, 959], [796, 959]]

【讨论】:

  • 哦,那是真的,我会编辑它。我想要 C 或 C++ 语言。对此感到抱歉。
猜你喜欢
  • 2012-11-04
  • 1970-01-01
  • 2016-04-24
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-10
  • 2018-07-04
相关资源
最近更新 更多