最适合坐标的容器

4
我目前正在尝试使用xlib从txt文件中提取坐标,我一直在想什么是最好的容器来完成这个任务?考虑到我的程序将要处理三角形和最短路径算法,我认为多维数组可能是最佳选择。我还想问一下如何使用scan函数来填充这个容器,计划是使用嵌套循环来填充它。
编辑:我打算使用的txt文件是一个三角形坐标列表,用于使用xlib函数绘制。然后通过在界面上放置点来找到从用户定义的位置到另一个位置的最短路径,三角形作为障碍物。
int main(int argc,char *argv[])
{
    int A,B;
    int Trig[A][B];
    FILE * pFile;
    // First need to scan the file. Need to check if there's a file to look into first.
    std::string pFilename = argv[1];
    if (pFilename == ""){
        cout << "Needs a Filename";
    }
    pFile = fopen(atoi(pFilename),"r");
    // scanf(pFile,"%1s (%d,%d) (%d,%d) (%d,%d)",);
return 0;
}

2
在C++中不允许使用int Trig[A][B];(更糟糕的是,您还没有初始化AB)。 - Alan Stokes
1
你需要更详细地说明你将如何处理数据;正确的数据结构完全取决于此。如果你不知道,可以从一个简单的“point”类的“vector”开始。 - Alan Stokes
我添加了更多关于三角形坐标的信息。 - Marorin
2个回答

3
如果这些是二维坐标,std::pair 是一个很好的选择。
#include <utility>

int main()
{
  std::pair<int, int> intCoordinates(5, 3);

  std::cout << "x: " << intCoordinates.first;
  std::cout << "y: " << intCoordinates.second << "\n";

  // -- hocus pocus, array of pairs, use it as normal C array
  std::pair<int, int> arr[5];
}

当然,您可以更改变量的类型。如果您愿意,它可以是 <double, double>,甚至可以是 <double, int>,完全取决于您。

更多信息:http://www.cplusplus.com/reference/utility/pair/pair/

这种或任何其他情况下,Point结构体都可以胜任:

struct Point {
  int x, y;
  Point(int a, int b) { this->x = a; this->y = b; }
};

int main()
{
   Point p(2,3);

   // ...
}

我们可能无法给出更多建议,除非您提供有关您的代码的更多信息。

2
“pair”通常不是除了两个任意数据之外的好选择(请参见例如http://maintainablecode.logdown.com/posts/158531-stdpair-considered-harmful)。几何点值得更具表现力的抽象化。 - Alan Stokes
我添加了更多关于程序意图的信息。 - Marorin
那个 Point 构造函数需要一个初始化列表。 - JorenHeit
我是指成员初始化器,抱歉。 - JorenHeit
虽然这听起来是个好主意,但我想知道从详细坐标的txt文件中收集所有点的最佳方法,因为我需要使用该源来制作三角形。 - Marorin

0
我最近遇到了同样的问题,并找到了这篇帖子。我开始使用建议中的pair,但最终发现它并不容易使用和维护,所以我创建了自己的Struct,并加入了一些实用的操作符。
.hpp
struct Coordinates
{
    std::size_t x;
    std::size_t y;
    Coordinates(std::size_t x, std::size_t y);
    void add(std::size_t x, std::size_t y);

    Coordinates operator+=(const Coordinates &coordinate);
    Coordinates operator+(Coordinates coordinate);
};

.cpp

Coordinates::Coordinates(std::size_t x, std::size_t y) : x(x), y(y)
{
}

void Coordinates::add(std::size_t xAdd, std::size_t yAdd)
{
    x += xAdd;
    y += yAdd;
}

Coordinates Coordinates::operator+=(const Coordinates &coordinate)
{
    add(coordinate.x, coordinate.y);
    return *this;
}

Coordinates Coordinates::operator+(Coordinates coordinate)
{
    return coordinate += *this;
}

以下是您可以做的:

Coordinates myPoint(4, 7);
myPoint += Coordinates(2, 3); // myPoint now contains x = 6 and y = 10

您也可以通过 yourPoint.xyourPoint.y 进行访问 x 和 y 字段。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接