坐标的最佳容器

Best container for coordinates

本文关键字:最佳 坐标      更新时间:2023-10-16

我目前正试图从使用xlib的txt文件中拾取坐标,我一直在想什么是最好的容器用于这样的努力?我在想多维数组,因为我的程序将与三角形和最短路径算法一起工作,我也想问如何最好地填充使用扫描函数的容器,计划是使用嵌套循环来填充它。

编辑:我计划使用的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;
}

如果这些是2D坐标,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/

这个或任何其他情况下,点结构体将完成工作:

struct Point {
  int x, y;
  Point(int a, int b) { this->x = a; this->y = b; }
};
int main()
{
   Point p(2,3);
   // ...
}

我们可能无法给你更多的建议,除非你给我们更多关于你的代码的信息。

我最近遇到了同样的问题,发现了那篇文章。我开始像这里建议的那样使用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。